The Objective-C Language
Pages: 1, 2, 3
The implementation file
The implementation file is where the meat of your class is coded. This file contains all the source code that gives your methods substance -- that allows them to do something useful. Remember now that the interface file is where your class is described, and this is the description programmers are to use to incorporate your class into their code. The implementation file is where you do your work.
The implementation file follows a similar format as the interface file, as shown below.
#import "ClassName.h"
@implementation ClassName : ItsSuperclass
{
instance variable declarations
}
method definitions
@end
Every class implementation must import its own interface file. Because the interface declares the supeclass and the superclass from which your class inherits, these things can be omitted from the implementation file. This reinforces the concept of the implementation being purely devoted fleshing out the methods. Thus, in practice, the implementation file only need contain the following code:
#import "ClassName.h"
@implementation ClassName
method definitions
@end
Methods are defined much like C functions are defined. The name is written exactly as is done in the interface file (without the semicolon), and method implementation code is contained in a pair of braces following the name. For example, our Circle class might have the following methods:
|
|
+ alloc
{
your code
}
- (void)setXLocation:(double)x yLocation:(double)y
{
your code
}
You may be wondering why + alloc has not returned the data type. The default return data type in Objective-C is type id -- that is, an object is returned by default. The + alloc method is designed to return an object of the class, and thus no return type need be specified. While we're on the topic of the alloc method, I should mention that you will rarely need to implement + alloc on your own. The NSObject class takes care of this. + alloc's purpose is to allocate (hence the name) memory space for newly created objects. The following sections will go into more detail about creating new objects.
Instance variables can be referred to in your method definitions directly. All instance variables are within the scope of each method without explicitly saying so. They are analagous to global variables in C. Thus, we could simply define the second method above as follows:
- (void)setXLocation:(double)x yLocation:(double)y
{
xLocation = x;
yLocation = y;
}
It is also possible to have local variables with more limited scope within each method. For example, in the second method above, we could insert a useless intermediary variable:
- (void)setXLocation:(double)x yLocation:(double)y
{
double tempX;
double tempY;
tempX = x;
tempY = y;
xLocation = tempX;
yLocation = tempY;
}
If I may go out on a limb, you could say that anything that applies to standard C functions, also applies to methods of a class.
Creating new objects
New objects are created by sending an alloc message to the class object of the class you wish to make an instance of. For example, if we wanted to create an instance of the Circle class, we would do the following:
id aCircle;
aCircle = [Circle alloc];
Remember, alloc returns an object, so the variable that refers to the instance you're creating must also be of type id. Once a new instance has been created we must also initialize its instance variables. This is done by issuing an init message to the newly created object.
[aCircle init];
Initialization must occur directly after allocation, so it's more common to create new objects by nesting the two messages above.
aCircle = [[Circle alloc] init];
By default, init initializes all the instance variables to zero. You are free to create your own initialization methods, called constructors, to initialize the variables as you see fit. By default constructors begin with "init". Because a constructor must interact with instance variables of an object, it must be an instance method, rather than a class method like alloc. For example, you might have a method in our circle class to initialize the circle with a radius of 10. This method would look like this:
- (void)initWithRadius:(double)r;
{
radius = r;
}
Any instance variables not initialized in your custom constructor will be set to zero by default.
In Project Builder
|
Also in Programming With Cocoa: Understanding the NSTableView Class |
I haven't talked about Project Builder just yet, but I just wanted to touch on a feature that relates to the current discussion. Project Builder contains templates for class interface and implementation files. What you get is a skeleton of a class that inherits from NSObject in the Foundation Framework -- all you have to do is flesh it out with your data structures and methods. So, now you both understand the struture of a class in source code, and how to make one with less work.
It won't be long now before we finish up with the nuts and bolts and get into programming real applications. Next time, I will introduce you to Interface Builder. Our foray into Interface Builder will be largely experiential. In the next three columns, I will go through two complete applications where you will see how Interface Builder and Project Builder work together to make your programming more enjoyable. See you then!
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 51 of 51.
-
Comments
2004-08-30 11:40:19 hEADcRASH [Reply | View]
-
Comments
2004-09-04 15:38:20 eflexx [Reply | View]
Class methods are methods that can be called on a class without any instance objects being created. They can be used without creating instances of the class. If you are familiar with the Java programming language, this is analgous to a "static" method.
Instance methods on the other hand are methods that involve a specific instance of the class, and therefore require an instance to exist to be used.
Methods like alloc shown above need to be class methods since instances have to be created even when you have no instances created yet; ie. when there are no instances, you cannot call instance methods.
An example of an instance method might be if you had a class Door with a method "open." open is an instance method because it needs only involve the instance of Door in question. In other words, you dont want to have to open all Doors at once every time you call open, so you call it on the Doors you want opened.
Hope that helps.
-
Multiple implementation files
2004-08-20 13:51:46 bbrady [Reply | View]
Is it possible to use multiple source files for a single class? It is possible in C++, but I haven't had any luck with Obj-C.
-
Learning from this
2004-06-27 05:59:31 MathieuTozer [Reply | View]
I'm keen on learning how to create applications in Cocoa and this helping me alot with understanding the key concepts of OOP - I only had a vauge idea after self learning from various sources. I look forward to reading on!
-
typos, etc.
2003-11-20 15:51:50 anonymous2 [Reply | View]
> Class methods can only be performed by
> the class object discussed above...
Only it's not clear exactly where it's discussed. For instance, a search doesn't turn up the phrase "class object" anywhere before this sentence.
There's also a spelling error/typo in example code "declerations" should be "declarations".
The article (and the books) should go a lot further, building on what it's covered, showing more and more about how the pieces of the framework can fit together, or be glued together with over-rides, to make useful programs.
-
odd phraseology
2003-09-14 19:17:38 anonymous2 [Reply | View]
this series of articles is a nice introduction to cocoa objective-c development and i appreciate it a lot, but the author uses some strange phraseology. example: "So, now you both understand the structure of a class in source code, and how to make one with less work." doesn't that sound like the author only expects two people to be reading this article? why not say "So, now you understand both..."?
that example is benign, but it can get confusing: "New objects are created by sending an alloc message to the class object of the class you wish to make an instance of." see now, i would've thought that i'd send an alloc message to the class object of the class that i didn't wish to make an instance of. how about just sending an alloc message to the class i wish to make an instance of?
-
setImage?
2003-03-02 05:11:21 anonymous2 [Reply | View]
What is the problem with this code snippet? I want to set the picture 'play2.tif' on the button when the same button is pressed. I am new to Cocoa
- (IBAction)ButtonAction:(id)sender
{
[sender setImage:play2];
}
-
Hi newbie to objective C
2002-05-06 23:15:36 chrisdb3001 [Reply | View]
Are there any libraries available for connecting to an Oracle or DB2 database available for objective C. And is there any type of exception handling available within objective C so as to give an application or more gracefull exit rather than a core dump. It seems to me that objective C may be more prone to this behavior. Also what is the status of GNUStep and will GNUStep offer they same objects and methods that Apple has provided so that we don't have to code for two differing platforms?????
-
dead language revival?
2001-10-20 16:22:50 lookaround [Reply | View]
It's nice to see ObjC coming to the scene again. I considered this language dead. Nobody except Apple actually supports it. And it doesn't seem to be easy for Apple. Look how long it took them to make anything new like Cocoa. I think they've been making it since NeXT project ceased.
What's wrong with ObjC? Why it's hard to develop large projects with? Are there fundamental deficiencies that hinge the language to be used in real projects? Well, there’re quite a bit, if we compare ObjC with industrial strength languages like C++ and Java.
1. ObjC is not strongly typed language.
2. ObjC does not support data protection.
3. ObjC has horrible syntax.
4. ObjC development framework is very poor (except on Mac platforms). No standard framework exists.
5. ObjC is pure dynamical like SmallTalk. Thus it’s extremely slow.
There are more points, but even these 5 are enough to stop any experienced developer contributing his time and efforts to ObjC. I wanted to expand every point, but having looked at the date of the article release I figured that hardly anybody would read my post but the author of the article.
If you think I'm wrong or inaccurate, correct me. -
dead language revival?
2001-11-30 12:47:51 eepstein [Reply | View]
Programming languages evolve over time. For example, data protection was added to Obj-C in a fashion that borrows the idea from C++. And reflection was added to Java allowing dynamic hooks into the runtime in a fashion similar to Obj-C.
In the hope of exploring what makes for better languages, I want to propose turning your criticisms into questions:
1. ObjC is not strongly typed language.
Q: What are the advantages and disadvantages of both strongly and weakly typed languages? What about a mixed-language that allows compile-time type checking while being lenient about enforcement?
2. ObjC does not support data protection.
Q: What are the uses of data protection? Instance-variable and method levels of protection? Should this be a language feature or something that can be easily implemented within the language?
3. ObjC has horrible syntax.
-- A matter of opinion, and I partly agree. The question: "What are good syntaxes?" seems contrived. Instead I'll just say that as syntax is often a barrier to learning a language, and as some are easier to learn than others, we may wonder: What qualities should be sought in a language's syntax? I for one think that if a general syntax for most O-O technologies could be developed that would be a big help. The syntax of Java seems to be the fore-runner.
4. ObjC development framework is very poor (except on Mac platforms). No standard framework exists.
The need for multi-vendor support. I'm increasingly a fan of open-source. So maybe that's a criteria: that you can get a standard development package as open-source.
5. ObjC is pure dynamical like SmallTalk. Thus it’s extremely slow
Q5a: What are the advantages and disadavantages of a dynamic languages.
Q5b: How should speed/performance be measured? What about measuring the actual time to do real-world execution, i.e., measure the system performance. In that context is a nominal (.7) overhead at the invocation level an issue?
And I'd like to add a different question as well. One of the ways I like to think of languages/compilers is in terms of information. When one write code (be it in C++, Java, Obj-C, or any other language) much of the information is the design of the class hierarchies: their interelation, their names, what methods they have, etc. This information is the real intelligence of the system's design. If we look at a C++ compiler and compare the input to the output what we see is a great loss of information. After compiling a class "knows" nothing about itself. There's no way to ask for even the most basic information, like what's the name of the class or it's parent(s). (I understand that as of 5 years ago there was a push to correct much of this, so it might be dated. The issue here isn't a slight on one language or another, per se, but a comparison of features and values to see what collectively might be the best parts of diverse langauges.) So (again, as of 5 years ago) you were stuck writing silly little "getClassName()" methods that made available (usually via a hard-coded string of char) the information you'd just typed into your editor when defining the class. What this means, in short, is that the compiler loses a lot of information.
So the rule that I started to develop when looking at languages had to do with the basic question: how much information am I putting into my code that I'm not getting out from the compiler? For a procedural language this doesn't matter so much. In an O-O language, this type of information is generally very useful. And if, you want the power of a dynamic language this information is essential. At the end of the day I find that one does have good need of this "meta-information" and that access to it makes a language trully powerful.
I imagine this chain of discussion is as good as dead, but these long-un-experssed thoughts have been triggered by your comments. Thanks for that and perhaps if this is read it might start a fruitful discussion.
-
dead language revival?
2001-11-30 12:07:02 eepstein [Reply | View]
I too find this to be a bit on the flame-bait side, but as it re-raises a number of inaccuracies, I'll reply in the hope of addressing these.
First, support. To begin with, that's not true. The GNU compile, yes the one that runs on all Linux boxes and is used by just about everyone porting anything from Un*x to W*ndows, supports Objective-C. But further, let's look at languages. C and C++ came from Bell Labs. As part of the governement granted monopoly to AT&T all Bell Labs inventions (like the transistor) were in the public domain. The original author of Obj-C was still following the proprietary software model as the software market was shaking out it never made as main-stream a splash as C++. Sun was quite smart with Java: they gave it away for free -- as they knew that the days of paying for languages was likely over.
Paragraph 2 is pure flame bait and I'll instead try to address what ar actually very interesting questions that are listed by you as answers.
1. ObjC is not strongly typed. Yup. Thank goodness! You can do type enforcing in Obj-C (indeed that's the recommended approach for most APIs), but you don't have to. That means a simple revolution: software that is MODELLING the real world, remains software: that is, flexible. In C++ (and to a less extent in Java) you are wed to a class hierarchy once it's been created. In Obj-C you are not. You can have Rectangle objects in the same list as Elephant objects and still get ALL the functionality of each object instance (without knowing a-priori the object's type and doing a cast) AND you can still treat all objects generally -- invoking say, a -size method on all objects in the list. I.e., a software model remains a software model: fluid, not rigid. One other "feature" of strongly typed languages: they assume the programmer is stupid and terribly error prone and so programmers are not allowed to do anything beyong the limits of types. This is often a self-fulfilling prophecy: producing bad programmers. Weakly typed means you get the warnings if you want, but you don't have to fight with the language and build endless case or if-then-else statements to cast an object "back" to the type it already is. In short: the language never forgot the type of the object. Not so in C++. (In Java this is remembered, but -- at least before reflection was added -- the language won't tell you.)
5. Not so. Because the language is dynamic, it is actually faster. YES. Believe it or not, if you are doing any sort of non-embedded system Obj-C will be faster than C++. (remember, C++ was designed for light-weight hardware level programming to control the switches of a telephone network). Why? Because all GUI and database-driven applications end up having to implement a much weaker version of dynamism in code and this turns out to be slow. Take a simple example: the GUI "callback". A button is clicked and your application gets a call-back. Leaving aside the fact that this is actually a proceduraly hang-over from C and is NOT O-O in any way at all, let's just look at performance. The call-back's first job is to figure out what UI component (button, say) got clicked. That takes 2 things: code and processing time. The time to figure that out is more than it takes to do a simple method invocation in Obj-C. Moreover in Obj-C you have a true O-O language so you don't write procedural call-backs. The button has a settable target (ANY object, remember that weakly typed feature!) and a settable METHOD! (yes, any method on ANY object that has a signature of taking one parameter). In terms of code, you didn't have to write any. In terms of speed for a UI with 100 components you have an O(1) implementation in Obj-C -- add as many components as you like, the target-action paradigm means: one event, one function call. That's it. In C++ (and for that matter the way that Swing is built, uggh!) you have an O(N) problem : on average you evaluate 50 if-then-else statements per call-back. And you had to write the code. Dumb. Oh yes, and slow. Oh, and by the way, you have the same problem when fetching from DBs (it's what still sucks about EJBs : they are really slow). Having said all that, UIs in C++ don't appear slow. Let's put it in perspective: compared to the speed of a mouse click, or a round-trip to a DB, interpreted Perl is fast, so it's not like we run into a speed problem. And Obj-C is clever about the nominal per method overhead, it caches the methods as they are used. With "warmed up caches" a method invocation is about equivalent to 1.7 function calls. (On the first hit, before a method is cached it's about 2.5 function calls). I.e., negligible. Where speed matters, like writing an embedded Fast-Fourier Transform, you're going to do it in assembler.
So #5 is not only a non-issue in Obj-C it's a non-issue. With GHz chips the issue is development time, amount of code, maintenance, etc. I've been a developer for 16 years. 10 years ago I got religion with Obj-C. I since found myself writing C++ code for 3 years because that's what the non-technical decision makers at various clients had decided upon. (Hey, marketing does work.) The experience there is common industry-wide: without an object hierarchy everyone rolls their own. This re-invention of the wheel means the promise of component re-use is almost never realized. Without dynamism everyone implements a makeshift version of it: every class in C++ ends up having a "className()" or "get_class_name()" method tacked onto it.
-
dead language revival?
2001-11-20 11:38:08 gctwnl [Reply | View]
This message is flame bait, but for the people new to Obj-C let me put a few things straight.
1. This is false. Obj-C can be used both strongly typed and weakly typed. A better way to look at this is that Obj-C has both compile-time typing (what you call strong) and run-time typing (dynamic). Take your pick, for some OO-approaches only dynamic typing is feasible.
2. The best data protection is in your head. But aside from that, I cannot easily access the members of a class, they are private. As far as 'protection' goes in a programming environment this is equal to the 'private' members in C++.
3. A matter of taste, but in my (and many other's) opinion, Obj-C is far more elegant than C++. It is also a fundamentally better paradigm than C++ in the sense that even classes are objects in their own right. It is not just OO, but even it's OO is OO (and not, as in C++ 'grafted on'). You experience the difference when you want to do really dynamic stuff.
4. This is somewhat true. But we were talking about Mac Dev, right? (I think that there is a decent foundation framework as part of GNUStep btw).
5. This is absolutely false. Obj-C is not slow at all. First, all the really dynamic stuff is cached, and secondly, for the stuff where you really need speed (a lot of calculations for instance) you will do that in C, after all Obj-C is a superset. It is stupid to write a large calculation using messaging. On Mac OS X, you can even combine C++ and Obj-C (Obj-C++).
The phrase 'industrial strength' is somewhat misleading unless you talk marketing instead of technology.
And lastly: large projects do not suffer from whatever language you choose. You can build beautiful OO programs in just CC. It's a method, not a language.
-
Definitions of Interface/Implementation, it is in error to say ObjC defines these in seperate files.
2001-07-04 19:36:15 bigboytoddy [Reply | View]
Well, just being the nitpick that I am, here is another error...
ObjC does NOT require that interface and implementation sections be in different files. That is an error, they can and are defined in different sections, which by PRACTICE are seperated into different files. ObjC again does not require this, as per the following
%cat SomeClass.m
#import <allTheCrapYouWant.h>
@interface SomeClass : NSObject
.. declare ivars
.. declare the methods
@end
@implementation SomeClass
.. define the actions to be taken by selector matched methods.
@end
Just hope that clears things up. There are times, all the time that an interface and implementation are included in ONE file, especially in OPENSOURCE projects where you are defining private classes that you DON"T want the interface to be well known, and in fact should NOT be known.
\t
-
Definitions of Interface/Implementation, it is in error to say ObjC defines these in seperate files.
2001-07-04 19:42:04 bigboytoddy [Reply | View]
I'm replying to my own post so that I don't clutter up the entire first level with comments/points/corrections.
If we are using a OO hybrid-language, and OO supporting libraries, it makes sense to use OO then in our code.
The following
double radius;
double xLocation;
double yLocation;
NSColor *color;
Should be replaced with
NSNumber *radius;
NSNumber *xLoc;
NSNumber *yLoc;
which allows much more consistant usage of the language and the functionality of the method selectors in the frameworks and work of other developers (MiscKit for OSX and such).
This again is one of the PROBLEMS of ObjC, that folks coming over from C continue to use the C definitions, when in fact there is optimized and highly effective means to use objects throughout the language. Apple has done a fairly good job in providing most structures and primative data types with higher level object wrappers. Please, folks, including the author, use them. You will thank yourself and Apple later when the finally get to the point of OO'ing ObjC where it is more consistant.
\t -
Definitions of Interface/Implementation, it is in error to say ObjC defines these in seperate files.
2001-07-04 19:45:55 bigboytoddy [Reply | View]
"Every class implementation must import its own interface file."
This statement is just flat out wrong. You don't have to have them in seperate files. Every class implementation must have a cooresponding class interface, prior to the definition of the methods.
Again, they may be contained in the same file. I'll stop now, before I have to repeat myself again ;'P Read previous jibberish by me to see details on this issue.
-
Returned Data types of methods
2001-07-04 19:49:13 bigboytoddy [Reply | View]
In fact, I believe that the id reference is always 'self', unless it is explicitely changed, say as returning a substitute class or even having it poseAs?, so if this true (I'm having a brain fart right now) it would conclude that in class methods '+' that would be indeed the class itself, and in instance methods '-', self would be the instance of course. I stand corrected if I'm wrong, wouldn't that explain it clearer? LOL
\t
-
IMHO the right way to do setter selector definitions
2001-07-04 20:00:55 bigboytoddy [Reply | View]
Hi, this is not a correction, more of an opinion...
In the past, and currently the setIVar has always been assumed, and for reasons doing with Interface Builder, the method say for iVars defined in the @interface as
@interface YourClass : NSObject
{
id someVar;
id someOtherVar;
}
// no need to define setters in the interface,
// by default they are already called if you
// define them in the implementation, the runtime
// (folks, you should read the runtime stuff if
// you have not already, those low level C functions
// will really clear things up for you about how
// things are done, management of selectors in
// the class structure, creating new methods on
// the fly if you wanted, say for behavioral
// based systems, adding interfaces to live
// classes, all kinds of cool stuff) will call
// the automagically, maybe that has been removed... but back to the real issue of naming.
@
@implementation
- setSomeVar
{ // do something useful, gets called upon initing
// allowing setup of vars... I think this still
// exists, yet I could be so old and decrepid
// NeXT/Apple may have taken this out
}
- setSomeOtherVar
{ // same as above, gets called automagically
}
@end
Now I hope Apple has stopped this, for obvious
reasons, it was undocumented and also really
messed things up when you wrote code, and didn't
know the side effects.
Basically it boils down to this, and is related
to the ramblings above. In Smalltalk, there
is a practice of naming (and it is good) for
getters and setters, 1/2 of which is follwed
for them most part in the ObjC community. I
highly recommend folks do this also...
The colon is part of the naming convention, yet
is really useful as a 'setter' word, indicating
something is being set... It is pretty obvious
when reading code that something is an iVar, without
explicitely telling them in the name, we all read
enough of it eventually to know with naming things
right, a method named
- center // would return the center of an object
- center: newCenter // would set same
That is it, instead of this stuff like
- getCenter // which I still see in code reviews
- setCenter: newCenter // which is redundant
That is it, tangential stuff aside, this is the
whole of my point, the ':' is part of the selector
definition, and unfortunately we often only use
it to visually seperate the selector from the
variables, in reality it is PART of the selector
itself and has value, especially in such obvious
settings.
Best wishes, I do hope this helps.
\t
-
Calling [super init] within your own initXXX methods
2001-07-04 20:13:20 bigboytoddy [Reply | View]
Hello again.
It was pointed out that your method for init (custom derivations and default initializer) would look like this for the class Circle...
@interface Circle : SomeOtherClass
{
double radius; // should be NSNumber IMHO
}
- initWithRadius: (double)r;
@end
@implementation Circle
- initWithRadius: (double)r
{
radius = r;
}
@end
In reality, this could and likely will be troublesome. It assumes there is no additional initialization done by the parent class... Bad assumption, really bad.
The correct way to define a default initializer method is more like
- init
{
return ( [self initWithX: defaultValueForX ] );
}
// This is the designated init method for this class
- initWithX: valueHolderForX
{
[super init]; // us the default initializer for the super class, init can be assumed, yet it would help to know your parent implementation since indeed you are inheriting functionality from it, makes sense to know it. There may be specific default initializers that are more useful and appropriate for your use.
// set your iVars here
x = valueHolderForX;
[ ... maybe private iVars are set here ... ]
}
Hope this helps.
\t
-
C
2001-06-11 23:22:07 flump [Reply | View]
I'm very interested in Objective-C, but I don't have any more than a basic knowledge a C. In fact so basic that I find myself confused with a lot of what's in these articles. I was wondering if someone could suggest some books to help me get a better grasp of C. -
C
2001-10-06 10:58:34 mariox19@mac.com [Reply | View]
I'm in sort of the same boat. Here's what I'm doing: I'm learning Java, for the following reasons.
Java is an object-oriented language and it's somewhat easier than C++. The syntax is so similar to C, I was able to breeze right through learning the syntax.
There are a lot of good books on Java, and what I think is most important is to learn the object-oriented concepts and get a lot of practice writing small programs with them. The second good point is that you can program in Cocoa with Java (there's a simple tutorial that comes with OS X).
I'm finding that I'm having an easier time grasping these concepts with the materials available for Java. I have Apples Objective-C book and the Learning Cocoa book, but I didn't have much luck with them.
Now, after studying Java a little bit, I find that I'm having an easier time understanding them, and am convinced that my understanding of Cocoa and Objective-C will improve if I dip into the documentation, now and then, while I'm studying Java.
I think people in our boat are going to have to sit tight until some more books on Cocoa and Objective-C are available. Fortunately, several are on their way by the end of the year. (Search "Cocoa" at Amazon.com!)
In the meantime, don't beat your head against the wall with this stuff -- get a good book or two and learn Java.
-
I want to Cocoa !
2001-05-14 03:15:14 zenarcade [Reply | View]
This is just excellent. for all coders out there wanting to cocoa, O'Reilly Network are building up a cocoa community. This is my website of choice.
keep up the good work and . . .would it be possible to make the stoies into pdf ?
tom -
Answer: Easy PDFs of O'Reilly Articles
2001-05-14 09:26:49 Derrick Story |
[Reply | View]
I'm glad you brought up the PDF question. I've been thinking about offering certain aritcles, such as the Cocoa series, in PDF format.
But then it dawned on me that anyone running Mac OS X can make their own PDFs in a matter of seconds. If you go to this page on Apple's site:
http://www.apple.com/macosx/
They have an excellent mini-tutorial on how to generate PDFs from web pages.
If you want to make a PDF of one of our O'Reilly Network articles it's easy:
1. Select the "Print this article" option at the top of each of our articles. This will give you one continous layout with a minimum of ads.
2. Then follow the steps to make a PDF from a web page (for Mac OS X users only).
This is a great feature of the new operating system.
-
Ojective C Language-Learning Cocoa
2001-05-09 12:34:38 ozoneranger [Reply | View]
great stuff
keep it coming.........
I will be a customer of O'Reilly books now due to this author
Ron
-
Question
2001-05-08 12:38:40 uwiz [Reply | View]
I have a question concerning the following syntax:
- (void)setXLocation:(double)x yLocation:(double)y
I don't understand the yLocation:(double)y part.
Isn't yLocation an instance variable in the given
example? Why is an instance variable listed in
a method declaration?
thanks
-
Question
2001-05-08 15:20:23 Michael Beam |
[Reply | View]
P.S. In the method under scrutiny here, the name of the method without the arguments is:
setXLocation:yLocation:
So you see yLocation here isn't refering to the instance variable, but is just part of the name. Also, the reason we have uppercase "X" and lowercase "y" is purely a matter of aesthetics. If the arguments were reversed then I would have written an uppercase "Y" and lowercase "x":
setYLocation:xLocation
I just like having new words or standalong letters in variable and method names start with an uppercase letter. Purely a matter or preference.
Sorry if this was redundant with my last message, i'm just trying to attack it from all angles. -
Question
2001-05-08 15:12:51 Michael Beam |
[Reply | View]
Yes, yLocation is an instance variable for the class. "yLocation" the text is also part of the method name described. The reason i choose this name is to provide information about what the argument following the colon sets. you could have replaced "yLocation:(double)y" in the method declaration with "locationOfYCoordinate:(double)y" if you wanted. I just choose "yLocation" because ultimately that is the instance variable being set to the value of the second argument in this method.
hope that helps clear things up!
Mike
-
Question
2001-05-10 14:41:38 kcrawford [Reply | View]
I'm still confused. You put the arguments inside the name of the method?
Please show the same method written in Java so I can translate.
Would it be:
public void setXLocationyLocation(double x, double y){} -
Question
2001-05-11 06:13:54 Michael Beam |
[Reply | View]
that's right, you put arguments in the name of the method. Think of it as each argument having a label that is part of the method name. Your java line was correct, although i think you meant to put in a Y before the second location
public void setXLocationYLocation(double x, double y) {}
-
Question
2001-05-11 09:19:15 kcrawford [Reply | View]
Thanks, that clears things up a bit.
Would you call the method with multiple arguments the same way--with the arguments inside the method name?
For example, would you call the method
- (void)setXLocation:(double)x yLocation:(double)y
like this
[setXLocation:10 yLocation:20]; -
Question
2001-05-11 12:00:20 Michael Beam |
[Reply | View]
Yeah, that's right, except your method call has no receiver, and it should. So it would have to be
[anObject setXLocation:10 yLocation:20];
when you want to invoke it.
-
Great Article
2001-05-08 08:04:00 angusliii [Reply | View]
Great Article - one request for the first program that you go through, could you explain (in detail) the elements of each line of code like you did for the third article just to reinforce the ideas and terminology. Most tutorials (especially Apple's) assume to quickly that you have gotten it by giving only one example so its hard to compare what you think you know because you cannot cross reference it with anything else. Otherwise I look forward to reading the next articles they are great - especially the cross references to C (I am jumping from C to objective C (no C++ here).
Thanks
Andrew Edmondson -
Great Article
2001-05-10 14:48:14 kcrawford [Reply | View]
I agree that this is exactly what many of us are looking for. Great job.
I am coming from a Java background, so references to that would be very helpful as well. Especially since you can write for Cocoa in Java (though I know it is not recommended for speed reasons). -
Great Article
2001-05-11 12:02:48 Michael Beam |
[Reply | View]
Thanks! I'm glad you (plural, for all the posters here) like it. I wasn't sure how many of the readers would be familiar with Java, so i was a little hesitant to show analagous Java syntax. But i think if people want to see that i'll add things like that in a conspicuous way.
-
Great Article!!
2001-05-05 22:17:29 gskluzacek [Reply | View]
Great Article!! Can't wait for the next one!
My only complaint, and its not really even a complaint, is that I wish the articles were longer! And I wish I didn't have to wait so long in between articles either.
Great job Mike!
PS. I'd like to see somthing regarding how to do network programming. Is there a framework or toolkit in Cocoa to do things like open a connection, write some data to it and the read back the response, and events that tell you when data arrives, etc.
-
Excellent Articles
2001-05-05 15:04:42 kakil [Reply | View]
This is very well done. Please keep the articles coming!!!
-
Great to see
2001-05-05 02:05:07 tpriest [Reply | View]
As a user who would like to start programming in Cocoa (Objective-C) I am glad to see a subject like this. What makes it so much better is that you are making it easy for me to learn.
Great stuff
-
Love it
2001-05-04 18:54:41 duthanas [Reply | View]
Keep up the clear explanations and simple examples!
I can't wait until the next installment.
-
Syntax error on page 3
2001-05-04 16:41:57 fozztexx [Reply | View]
On page 3 you've got syntax for @implementation which is totally bogus. There's no :ParentObject in @implementation nor is there any declaration of instance variables in @implementation. That's all done in @interface.
-
More, more!
2001-05-04 11:31:31 mprogers [Reply | View]
I don't know about everybody else, but I've found this column well written, and easy to comprehend. I can't wait to read more.
Michael Rogers
mprogers@mail.millikin.edu -
More, more!
2001-05-04 16:16:33 Derrick Story |
[Reply | View]
I've been reading the upcoming columns, and you'll be happy to hear that the series gets even better in the coming installments. [Editor's Note]
-
+ initialize
2001-05-04 10:14:46 wheatis [Reply | View]
This was fine article. Although you mentioned that the +alloc method is usually not implemented, using it as the example could be misleading to new Cocoa developers.
+ initialize would have been a good alternative method to use as a demonstration of class methods. It gets called when the class is first loaded into the run time, providing an opportunity to do any class level initialization that needs doing. While one rarely (you can probably say never) provides an implemention for +alloc in new Objective-C Cocoa class, there are usually more opportunities in the wild to give +initialize an implementation.
- wheatis -
+ initialize compared to constructors in C++
2001-05-05 22:28:14 gskluzacek [Reply | View]
I'm fairly familiar with C++'s constructors, that get called immediately (and implicitly) when a object is created. Why in the Objective-C code do you have to explicitly call the +initialize method? I would think that this would allow errors to occur in unexperienced programmer's code. I would think that C++'s way of calling the constructor whenever a new object is created would be preferable. Just my uninformed opinion, as I am just learning Objective-C myself. -
+ initialize and - init /not/ compared to constructors in C++
2001-05-06 16:55:40 halliday [Reply | View]
Neither the + initialize class method (spoken of as a replacement
example to the + alloc class method, since it's more likely to
be implemented by a programmer), nor the - init method
(referred to by the articles author as being like a constructor) are much
like C++'s constructors.
C++'s constructors are b*st*rd (I mean it in the non Vulgar Slang senses
of the word) combinations of allocation (implicit in C++'s constructors)
and initialization (what all the code actually contained in the constructor
is supposed to be doing: And since, at the time the constructor
is called, an instance of the object isn't fully defined, dire consequences
can intermittently befall the programmer that tried to do otherwise).
The existence of constructors in C++ has more to do with the fact that
instances are created using a "know nothing, third party" new
operator than to any inherent desirability (yes, I do know about stack
allocated instances, but even that can be done in a more accessible method
if C++ had any true concept of a class object and class methods,
but I digress). (Incidentally, Objective-C used to provide something
sort of similar with + new class methods [except allocation and
initialization were still explicit, allowing the programmer maximal control],
and, yes, these were the methods used to create stack allocated instances
for those language versions that supported them, but this practice is now
deprecated [it provides no new functionality].)
Incidentally, the mention of - init methods being anything
like constructors is the sole problem I have with the article.
Well, that and the related problem that suggests that it's - init
that defaults to initializing all unmentioned instance variables to zero:
This is actually done by the way the memory is allocated in the
+
alloc method (once the + alloc method exits one has a fully
functional instance of the class, with all instance variable initialized
to zero or null or nil, as the case may be [well, actually,
there is the case of the, essentially, hidden instance variable called
isa,
but suffice it to say it's appropriately initialized as well]). One
never has to deal with partially existent instances, as C++'s constructors
do. -
+ initialize and - init /not/ compared to constructors in C++
2001-05-07 10:45:12 Michael Beam |
[Reply | View]
I stand corrected about + alloc setting all instances variables to zero rather than - init.
Additionally, when i said init is like a constructor, I was thinking in the sense of Java. I could see the two things being equivalent for a class (say the class is a circle).
Java Constructor:
Circle aCircle = new Circle(10);
where the argument for this constructor is the radius of the circle. In Obj-C this might look like:
Circle *aCircle = [[Circle alloc] initWithRadius:10];
If I was being loose with OOP terminology, I apologize. -
+ initialize and - init /not/ compared to constructors in C++
2001-05-07 21:08:18 gskluzacek [Reply | View]
Heck, I didn't mean to open a can of worms. I just wanted to say I like the way C++ implicitly calls the constructor of a class to initialize the object, where it looks like you have to explicitly allocate memory and initialize the object in Obj-C. While not being anything except a beginer in Obj-c, I was just wondering why the designers of the language decided to go with this explicit route of initializing its objects. Seams to me IMHO, like there be more room for error.
Regards,
Greg -
+ initialize and - init /not/ compared to constructors in C++
2001-05-08 12:27:34 Michael Beam |
[Reply | View]
Hey Greg,
Here's a line from Apple's Objective-C book:
"Separating allocation from initilization gives you individual control over each step so that each can be modified independently of the other."
I don't think there would be too much room for error for a programmer as long as he remembers to do the two steps. There isn't much room for variation in the alloc/init procedure it seems. For Class developer's though, this might come in handy to have this livele of control. This probably didn't help much, but i thought i'd let you know what i read from the Mouth.
Mike







I am also unclear about class methods and instance methods. Are these analogous to private and public methods?