I was wondering if anyone would be kind enough to define what a class, instance and method is in Objective-C or point me in the right direction or a good Objective-C learning resource.
Thanks!
For understanding the basic concepts, read the Wikipedia article on OOP.
Once you've understood that, the next step is to read up on Objective-C. For example, there's a nice document from Apple which you should read, and then there's the Objective-C Beginner's Guide. Apart from that, just search on Amazon and pick a book that has good rating/comments and that also covers topics you're interested in, like developing for the iPhone. Most iPhone development books start by giving a (short) introduction to Objective-C.
Once you have gotten your hands dirty with writing some Objective-C code, I recommend reading Cocoa Design Patterns. Do not read it as your first book, but do read it some day ! It explains why the Apple APIs (Cocoa) are the way they are, it explains the concepts and patterns you see in Cocoa. It's not a step-by-step guide but gives an understanding on how things work together.
As a start I'd use apple's Objective-c Primer: http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/
I'd also adise you to look for tutorials about "Object Oriented Programing", to learn its basic concepts.
But to answer your question:
A class is like an Object type. You write the definition of your classes in your source code. In objective-c this happens in the #interface and #implementation parts. An example for a class would be "cars".
A class has class variables: usually of a simple type, like int or bool, or a pointer to another class. A class also can have methods, which are like methods, or functions in sequential programming (c, or similar). A class method for "car" could be "change tires", an class variable could be "license plate".
These are merely definitions of how your class looks like and how it behaves. Like the fact, that integer is a number. which number any int in your program is, would be the instacne. Or to use the "car"-example: "car" is the class and the silver-coloured, mercedes with the licence plate number 'xy-123' is an instance of the class.
Have fun coding!
Class = Car
Instance = Tire
Method = turnLeft
#interface Car: NSObject {
id tire;
}
#property id tire;
- (void)turnLeft;
#end
Related
One of the most frequently asked questions on iOS developer interview is - difference between abstract classed and interface.
I don't know an answer and i don't get it neither. Interface is a section of class, when you declared methods. it could be open for other classes (public, .h file) or hidden in implementation.
Abstract class is a class, that is only used to create hidden subclasses and it should not have own init methods (if i understand correct).
So, what exactly is answer for that question? And what does that question mean?
I did spend time searching for an answers, but answers wasn't related to Obj-C, so i can't figure out by myself.
I hope someone could provide clear answer and that question would be helpful for those guys, who want to pass an interview.
A good way to approach this problem is first think about it in general programming theory, and then in more concrete Objective-C context.
Abstract Class - is a class intended purely for subclassing, one must not instantiate it. Abstract class declares something and has also the implementation for that.
What is the reason for having such special class? It is modelled after real life! :)
Imagine an abstraction - an animal. What has each animal in common? They are all alive (and can die). They need to eat. The can move in space. These traits are common and fundamental to all animals. I heaven't heard about an animal that doesn't needs food, cannot move and lives forever. Other then that there is a LOT of not so fundamental differences between various animals.
There is no animal on the planet which is purely an abstract animal like that. That set of fundamental behaviours, traits is simply not enough to be a concrete animal..
There is an implied principle, that to be a concrete animal, you have to have some additional traits besides those fundamental ones.
Now, in programming, we need to be able to somehow
express these fundamentals (interface declaration)
have a way of describing how they work (implementation)
attribute them to a class
prevent instantiation
ensure that any concrete animal will have them (inheritance)
We know, what these fundamentals are (declared public interface) and we know in practice how they manifest themselves concretely (implementation of those declared traits). We want them to be inherited by all concrete entities. So we do it in the abstract class because it satisfies these condition I mentioned. It contains all the fundamentals, has their implementation, but cannot be instantiated on its own.
Abstract class is an abstraction over a set of related entities that captures what is fundamentally common between all of them., tells us how it is done..and ensures all more concrete entities will inherit this.
Interface - is something less. Let's a have a real life analogy. Person, robot, animal, wind (a force of nature).
Some people can sing. A robot has a voice synthesizer module embedded so it can sing. The autumn wind touching my teracce glass "sings" a lot I can tell you. And Tinka (r.i.p) my dog, was actually a good singer too.
But really, "singing" between these four has the only thing in common - you can hear it as pleasing sound in your ears. How the singing happens for those four, differs a lot in reality. (implementation)
Another complication is, certainly not all people, dogs, winds, or animals can sing. Some of them can.
So how would we reflect this situation in programming? Via interface :)
You can have an interface called "SingInterface" which in our case has one behaviour/trait/functionality declared and it is sing. Interface simply declares something and that's it. Interface doesn't say how that something is done, there is no concrete implementation. Nor does it say who can do it, the trait in the interface is not limited to one type or one class really. (see http://www.nasa.gov/centers/goddard/universe/black_hole_sound.html)
Interface is a list of 1 to N traits/functionalities without knowing how concretely will they be realized, and that list of traits/functionalities that can be arbitrarily (no rules exist to who) attributable to entities from disparate sets that are fundamentally different (animals or robots).
Object oriented programming borrows many concepts from real life. That's why these analogies work so well.
In Objective C, contrary to some other languages (C# etc),
there is no language level support for abstract classes. It is not possible to enforce that a class is abstract during compilation. A class is abstract only by convention and respecting that convention by developers.
As for interfaces, a word "protocol" is used in objective C. It's just a different word for the same thing.
In objective C you can
code against the interface ..by declaring some object as
id<protocolName>
add additional functionality to classes by declaring that they conform to protocol which you do in the class interface
#interface ClassName <protocolName>
So, there might possibly be even a case where your class is a subclass of abstract class, and it also conform to some protocol.
Thanks to Rob Napier's comment at here. My answer is:
An interface is just the outside view of a class. What it reveals publicly.
In Swift you just write a class in a single .Swift file, and if ask Xcode to show you can generate its interface. Xcode will only then show properties/functions that are public/internal.
In Objective-C. You first have to manually write the interface...declaring what of the class is public and then manually write the implementation. An interface without implementation is not compilable. It's like you saying this is how my class will look like, but then you have provided nothing for how it implements the public methods or how you manipulate your properties—when you must (provide).
Abstract relieves you of how it implements
For abstract classes, you shouldn't provide any implementation, only that it would have such parameters or it would have such functions with such signatures. However an abstract class is compilable on its own. Because you don't need to provide anything more than that.
I am taking my first stumbling steps in the Objective-C world together with a book on the subject. I have now come to the stage in which to internalize the concept of creating and using a custom class.
And as I guess that understanding these fundamental concepts and principles correctly is key to my future learning of Objective-C, I just wanted to check with you if have grasped the concepts somewhat correctly.
So when creating a custom class, I have understood that this is done in two separate files – the public class header file, and the class implementation file. And in order to internalize this concept, I have metaphorically understood this with a parallel to a “magician” doing its tricks in front of an audience.
The header file is somewhat like the poster outside the theatre where the magician performs. Before entering, we can all see what the magician looks like (the properties) and what tricks he (it’s mostly a “he”) can perform (the methods), and on what types of stuff he can make his magic tricks (type declaration). Thus from this “public” poster (the header file) of the magician, I can understand what kind of magic he can perform and what props he is using. Maybe there is also a mentioning of that this particular magician has learned some of his tricks from the great Houdini (the class heritage and Houdini thus being the superclass).
If I were allowed backstage, I would then be able to actually see how he is doing his tricks, that is, I would be able to look in the magicians implementation file.
Would this metaphor be somewhat along the lines of how you can understand the concept of a custom class?
However, I have not yet quite figured out how the concept of class methods and instance methods relates to this metaphor?
Could you say that instance methods belongs to a category of tricks that this particular “instance” of the magician is performing in this particular show, and the class methods would be the tricks that contemporary magicians can perform?
Thirdly, it is a bit confusing the way methods are using “types”. Some seem to be declared up front in the interface file, and some seem to just be “declared” on the fly within the methods?
To take an example using the “Magician” class, my understanding of the header file might look like this:
#interface Magician : NSHoudini
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (rabit) FromRatToRabit: (rat) aRat;
#end
And the implementation file might look like this:
#import “Magician.h”
#implementation Magician
rabit aRabit
// rabit being the type and aRabit the variable
- (rabit) FromRatToRabit:(rat)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
aRabit
}
#end
If above is correct I wonder why the aRat variable that you “feed” the method with is not declared? Or is the declaration considered done when you are using it in the method description?
Your metaphor is acceptable. A header is an interface for other files to look at which tell them what is accessible to them from that class/file and its corresponding implementation file (if it has one)
I noticed in your code though that Magician is a subclass of Houdini. I might just be misunderstanding your example, but in terms of inheritance, that is probably incorrect. What you are saying there is that every Magician is a type of Houdini. It should probably be reversed to say that Houdini is a type of Magician.
Class vs Instance has been explained many times and is not specific to Objective C, so I won't get into it too much.
Here is a post with some good answers. Basically, a class function/variable belongs to the Class itself, and is not specific to any instance of that class. Another word for a class function/variable is a static function or variable.
Not sure what you mean by the last question. Every pointer/variable in objective c has a type.
Your syntax is messed up though, Here is what the code you posted should probably look like (and yes I corrected the spelling of rabbit :-P)
#interface Houdini : Magician
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (Rabbit *) FromRatToRabit: (Rat *) aRat;
#end
#import “Houdini.h”
#implementation Houdini
Rabbit *aRabbit; // this is an ivar, although you're not actually using it anywhere, I'm just correcting your syntax
- (Rabbit *) fromRatToRabit:(Rat *)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
[aRat doSomethingToReturnRabbit]; // assuming rat has an instance function that returns a rabbit
}
#end
And you could use this function by doing something like
Houdini *myHoudini = [[Houdini alloc] init];
Rat *houdinisRat = [[Rat alloc] init];
Rabbit *houdinisRabbit = [myHoudini fromRatToRabbit:houdinisRat];
Note that this depends on there being a rat class and a rabbit class (which you did not provide). I am also just using what are normally the default initializers.
Hopefully this helps, you should try searching more on the specific topics you have questions on individually, because there is plenty of reading available.
It's a great metaphor for understanding the divide between the public interface and the hidden implementation. But I think you might be getting a bit wrapped up in it and I do see two major misunderstandings - "Houdini" being the superclass and the class methods being "all tricks".
The common textbook way to evaluate the sensibleness of an inheritance hierarchy is to evaluate whether a subclass instance "is a" superclass instance. This can get very abstract in reality but if, say, you're designing the Magician's Guild medical insurance benefits processing software or something, in that context a Magician "is a" something that's definitely not a Houdini! Say they are all freelancers so every Magician "is a" 1099 Contractor (US tax form for self-employment income), or something like that. Another way to think of it would be to think Magician "is a" Stage Performer, which "is a" Entertainer, and so forth. Not that you always want to make software like this but it can help for learning the concept I suppose.
The second thing you said you were struggling with was how to think about class methods. Consider class methods behavior and information inherent to the type, and independent of any instance. Going back to the benefits software example, lets say all Magician guild members get a 401k (another US tax code thing, retirement account) with $X defined contribution per paycheck. Now assuming that's not something that varies with seniority, this would be a good piece of information to keep at the class level. So, all the tricks a magician can perform would not be class methods - Magicians perform them, so they would be instance methods. Perhaps a list of banned tricks (for being too dangerous) could be a class method - it's a rule inherent to being a Magician but is independent from any single magician.
Finally, to your third question about types, I can sort of guess at what you're asking but am not sure. Say you have a method
- (void)myMethod:(id)myArgument
{
NSLog(#"myArgument = %#",myArgument);
}
Then are you asking where myArgument is declared? It is declared right there in the method signature, where it's a parameter to the method and you can refer to it in its scope of the method body (within the curly braces). Not sure if that's what you meant by "on the fly" or not. I'm afraid you'll have to provide some actual source code, not pseudocode, and point out specific places you're wondering about.
And a couple of minor points on terminology, sorry this is getting so long - the term for "feeding" a value to a method is "passing" usually as a "parameter" or an "argument". The method "description" is usually called a a method signature, or declaration, sometimes prototype I hear. And yes, please clarify what you're talking about with types, type declarations, and so on, I'm not 100% clear on your questions there.
Hope this helps!
Learning basic Objective-C and have a few beginner questions.
How would I define and implement a method which takes two (or three) arguments within my class?
I find the syntax to pass multiple arguments into a method really confusing. I would really appreciate any help. thanks.
Apple's "The Objective-C Programming Language" document provides a nice overview of Object Messaging including an explanation of the syntax.
Here's an example of a simple 2-argument method implementation:
-(int)myMethodThatMultipiesThisNumber:(int)x byThisOne:(int)y
{
return x * y;
}
You would invoke it like:
int z = [myObject myMethodThatMultipliesThisNumber:6 byThisOne:9];
Is that what you're looking for?
Edit: Based on your comment below, it seems like you're missing a fundamental feature of Objective-C messaging - that the method name is interleaved with the arguments. Check out this page from The Objective-C Programming Language for all the detail you need.
Whether or not you are interested in iPhone programming, I would watch the first three classes of Paul Hegarty's CS193P class from Stanford.
Those first three classes have very little iPhone specific stuff, instead, classes 1 and three go over the features and syntax of Objective C, and class 2 goes over basic use of Xcode (which, if you want to do Objective C work, is likely the IDE you will be using). Other than the fact that it goes VERY fast (which may actually be what you are looking for) you would be hard pressed to find a better "quick overview" of Objective C.
We know that in Objective-C there are two main root classes: NSObject and NSProxy. There are other roots (mainly for private and legacy purposes) like Object, and NSLeafProxy.
Defining a new root is fairly trivial:
#interface DDRoot <NSObject>
#end
#implementation DDRoot
//implement the methods required by <NSObject>
#end
My question is: why would you ever want to define a new root class? Is there some use-case where it's necessary?
There are two primary reasons to create a new root class; proxying & a new object model.
When proxying, it can be useful to implement a new root class such that you can basically handle any and all of the class/object's behaviors in a custom fashion. See NSProxy.
The Objective-C runtime is flexible enough that you can support a new object model quite easily (where easily discounts the inherent complexity of creating such a beast in the first place). Actually, many of the behaviors that are considered inherent to the runtime -- KVC, KVO, etc.. -- are implemented as a part of the NSObject class itself.
I know of at least one company that -- as of about 8 years ago, at least -- had implemented their own object model as a part of building their ~500k LOC financial analysis engine.
The key, though, is that if you go this route, you don't try to make your classes interact with Foundation/CF/AppKit/UIKit, etc. If you need that, just subclass NSObject already!
It is interesting to note that NSManagedObject is effectively a root class in that it does some pretty seriously custom stuff, but it is a subclass of NSObject so subclasses of NSManagedObject are inter-operable with the rest of the system.
As far as I can tell, there should be no reason for creating your own root class, because short of implementing all of the NSObject protocol methods yourself, you're going to be missing out on a lot of functionality, and going to be making a lot of calls to the Objective-C runtime that should essentially be done for you.
Unless you really had to implement the protocol differently from the default (NSProxy is a special case that does have to), you shouldn't need to make your own root class. I mean, you'd have to be writing a class that cannot fundamentally be represented by NSObject and the protocol as implemented by Apple, and in that case, why are you even writing it in Objective-C?
That's what I think. Maybe someone can come up for a creative use for it.
(People researching the topic should go look at the NSObject Class Reference, NSObject Protocol Reference, 'Core Competencies: Root Class' document, and the 'Root Class' section of the Fundamentals Guide: Cocoa Objects document.)
Objective-C and Cocoa are separate things, and in principle it’s possible to define entirely new application frameworks that don’t use Foundation. The financial analysis people bbum mentioned are a practical example, and I believe they’re still around.
Another use is to make a proxy that’s more minimal than NSProxy, as Mike Ash does here.
Oh, and the private NSInvocationBuilder is a root class, presumably for the same reasons as Mike’s proxy. Capturing invocations for later use is something one might want to recreate.
Companies like the OmniGroup have defined a version of NSObject to use as their own base class for everything.
It's essentially a subclass of NSObject with some debug stuff. Other than that, it's usually a terrible idea to fight the framework.
Find Omni's code here:
https://github.com/omnigroup/OmniGroup
As you may have guessed from the question - I am right at the beginning of the Obj-C journey.
I'm hoping that someone out there knows of some diagrams that depict the relationship between classes, objects and methods - and that they're willing to share.
The problem I'm having is that just looking at code in a textbook doesn't completely explain it - for me at least.
Thanks for reading!
Regards,
Spencer.
No diagrams, but this is the tutorial I wish I'd read before I started:
http://www.cocoadevcentral.com/d/learn_objectivec/
Simple English, all the basic concepts.
Classes are just like classes in any language. They are descriptions.
Objects are like nouns. They are an instance of a class. That is, if you had a description of a generic book (the class) and you made a thesaurus based on that description, the thesaurus would be the object.
Methods are more or less functions. If the objects are nouns, then the messages are verbs.
[ScienceBook getTableOfContents]; //this would like return a table of contents.
Here, the object ScienceBook is being sent a getTableOfContents message (method). So now, the science book would theoretically find, format and return the table of contents to whom ever sent the message.
To some extent, diagrams may not be that helpful to answer the questions you present.
It may help to think of things like this:
A "class" provides the prototype or definition for some thing. For example, a "Person" or a "Car". A common synonym for "class" is "type".
An "object" is a concrete example or instance of a class. For example, you are an instance of "Person", and your car is an instance of "Car".
A "method" is a behavior, action or property of a class. However, a method is normally only meaningful in the context of an object. "Person" -> "Eat" is not meaningful, but "you" -> "Eat" is.
These are fundamental Object-Oriented concepts that are not specific to Objective-C. If you are interested in a general overview that is language-agnostic, I recommend "Object Thinking" by David West. Even though it's from Microsoft Press, it covers the concepts rather than any specific language.
I come from a fairly strong C++ background, but I can definitely remember when I started, I had a hard time grasping at the concept until I found a way to associate it with physical objects.
The word class and object you can use almost interchangeably. Think of an object as a container, like a bucket. The word bucket would be your "class". It is the name you give to the type of object you have.
A bucket has a certain purpose...to carry something. It might be water...or perhaps sand. So perhaps you want to fill the bucket. This would be something you do to the bucket, so in objective-c, this would be your method. You might write something like:
- (void) fillWith:(elementType)something;
So in this case, "something" might be something that represents and object you wish to fill your bucket with.
Your class might look like the following:
typedef enum items {
CRAYONS,
MARKERS,
SAND,
WATER } elementType;
#class Bucket {
elementType item;
}
- (void) fillWith:(elementType)something;
#end
Here's one link to some objective-c samples. Also try the apple development center.
If you're after information on Object Orientated Programming (ie the meaning of classes, objects, methods etc) then I'd advise against Objective-C. Objective-C on the Mac relies heavily on the Cocoa framework. The Cocoa framework is vast and performs a lot of 'magic' which will make it harder to understand the fundamentals of OOP.
An easier place to start would be a language used for web development. It's easier to get to the nuts and bolts of OOP with these languages.