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.
Related
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
Hey, I was wondering how Objective-C function declarations worked, and why I would want to declare another function besides main.
For example, I now that, at least from most programs I have been exposed to, Objective-C programs begin execution at the function named main, and the name main is therefore reserved.
Now, the reason we usually "return 0" at the end is to show that everything went normal, correct? And, because we specified main would be a function of type "int", or integer.
I was wondering how common it is, I guess it depends on the scale of the program however, to declare other functions besides main, and how I should do so.
UPDATE:
Actually, sorry, I found a pretty good guide right here:
http://www.techotopia.com/index.php/An_Overview_of_Objective-C_Functions
But additions are certainty appreciated! :)
Please don't mind for my question. Is Obj-C the first language that you are learning? I'm asking this as most of the things that you have asked is about general concepts of programming. About the main function or returning int, these all came from C. Remember, Obj-C is superset of C language. If you don't know C / C++, then I would recommend you to look at them before jumping to Obj-C. The reason is there are hundreds of C / C++ resources for the beginners. But I'm afraid there are not much on Obj-C for the beginners. For example, there is little possibility that an Obj-C text will explain in detail what a pointer is, what is dynamically allocated memory, what is recursive function, what is the role of object, what is static member etc.
May be I'm wrong. May be there are some texts on Obj-C for the beginners. Personally I have not searched one as this was not my first language.
You want to declare functions besides main() because a packing even a relatively small 5000-line program into main() would be completely insane. It would also contain lots of duplicated code since you aren't factoring common operations into functions.
I'm coming from AS3 to Obj-C, and classes are confusing me. I want to create a ball class as a test, with colour, radius etc. Looking through other people's code I've discovered they use structs to implement them, and this seems like a much nicer method. I've searched but am unable to find a really clear explanation of what structs are, and how to implement them.
In terms of my ball class, to implement it I'd want to use something like Ball *myBall = [Ball radius:(14), mass:(1)]; etc. This seems like a nice clean way to do it. Can anyone suggest some further reading on this?
Thanks.
Read Apple's own Objective-C Primer. It's worth reading. The documents linked there are also useful. You know, vendors (in this case Apple) often have a nice set of documentations because they need to sell their technology...
For a comparison of ActionScript and Objective-C, see this series of blog posts for example.
Using classes straight of the bat would be a better idea as once you start developing you'll probably want to extend the functionality like object orientated methods (what classes are for).
Creating a class for ball with an appropriate constructor and properties would fit your needs.
I recommend starting here.
I know there's no one answer to this question, but I'd like to get people's thoughts on how they would approach the situation.
I'm writing an Objective-C wrapper to a C library. My goals are:
1) The wrapper use Objective-C objects. For example, if the C API defines a parameter such as char *name, the Objective-C API should use name:(NSString *).
2) The client using the Objective-C wrapper should not have to have knowledge of the inner-workings of the C library.
Speed is not really any issue.
That's all easy with simple parameters. It's certainly no problem to take in an NSString and convert it to a C string to pass it to the C library.
My indecision comes in when complex structures are involved.
Let's say you have:
struct flow
{
long direction;
long speed;
long disruption;
long start;
long stop;
} flow_t;
And then your C API call is:
void setFlows(flow_t inFlows[4]);
So, some of the choices are:
1) expose the flow_t structure to the client and have the Objective-C API take an array of those structures
2) build an NSArray of four NSDictionaries containing the properties and pass that as a parameter
3) create an NSArray of four "Flow" objects containing the structure's properties and pass that as a parameter
My analysis of the approaches:
Approach 1: Easiest. However, it doesn't meet the design goals
Approach 2: For some reason, this seems to me to be the most "Objective-C" way of doing it. However, each element of the NSDictionary would have to be wrapped in an NSNumber. Now it seems like we're doing an awful lot just to pass the equivalent of a struct.
Approach 3: Seems the cleanest to me from an object-oriented standpoint and the extra encapsulation could come in handy later. However, like #2, it now seems like we're doing an awful lot (creating an array, creating and initializing objects) just to pass a struct.
So, the question is, how would you approach this situation? Are there other choices I'm not considering? Are there additional advantages or disadvantages to the approaches I've presented that I'm not considering?
I think that approach 3 would be the preferred way to do things. When you wrap a library you'll want to create wrappers around any object or structure that the user is expected to deal with.
If you wrap everything, then you are free to change the internal workings of your classes at a later date without affecting the interfaces that your users have become accustomed to. For example, in the future you may realize that you'd like to add some type of error checking or correction... maybe setting a stop that is earlier than the start causes some calculation errors, you could change the stop method in your Flow wrapper to set start equal to stop if stop is less than start (I admit, that's a really bad example).
I'd stick with approach 3. You're "just passing a struct" now, but the Flow object might expand more in the future. You say speed is not an issue and so I'd imagine memory consumption isn't either, or you would be sticking with C anyway.
My answer is not what you were asking, but it is still how I "would approach the situation".
The first question I would ask is, "what value does this wrapper add?" If the answer is, "to use Objective-C syntax" then the answer is "don't change a thing, use the library as-is because C is Objective-C syntax."
I don't know which library you are wrapping, so I'll use SQLite for an off the top of my head example. Using a layered approach, I would do something like this:
A) High level objects (Order, Customer, Vendor...)
B) Base class (Record)
C) SQLite
So the base class is written to call SQLite directly then the other classes work as regular Objective-C classes.
This is apposed to:
1) High level objects (Order, Customer, Vendor...)
2) Base class (Record)
3) SQLite Wrapper (Objective-C)
4) SQLite
The same application is created but there is extra work creating, maintaining and debugging level 3 with very little to show for it.
In the first version, layer B wrapped SQLite so nothing above it called SQLite directly AND it didn't try to provide all of SQLite functionality. It just provides the functionality that layer A needs and uses SQLite to achieve what is needed. It 'wraps' SQLite but in a more application specific manner. The same Record class could be reused in another application later and extended to meet the needs of both applications at that time.
Since Objective-C uses structures, why not leave it as a struct like NSRect?
Hi I'm writing this question because I'm a newbie in ObjC and a lot of doubts came to my mind when trying to make my fist training app. The thing is that I have a strong background in C, I've been programming in Java for the last year and I've done some collage stuff with Smalltalk (I mencione this because those are my programming references and those are the languages I'm comparing ObjC with).
The first problem I've encountered is that I don't know where to draw a line between ObjC and C, for example when dealing with math operations, Should I use math.h or there is a more "object-way" like you can do in Smalltalk (aNumber raisedTo: 3) ? How does a person with no background at all in C learns ObjC?.
Another thing that I couldn't find was a collection's protocol (I've looked over the Foundation Framework documentation given by Apple). Because I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Smalltalk or Java) or I gotta check by hand every collection and see if there is a cool method that my new collection should have.
I don't know if I'm being too stupid or I'm searching for features that the language/framework doesn't have. I want to program in ObjC with the ObjC style not thinking in C, Java or Smalltalk.
Sorry if the question was too long.
Absolutely use <math.h>. You don't way to pay message sending overhead for functions that run in 30 cycles. Even function call overhead seems pretty steep at that point.
More generally, use as much or as little of C-style as you want to. I've seen Objective-C that was nothing but a couple C modules glued together with objective C messages, and I've seen Objective-C that essentially zero lines of code without the square brackets. I've seen beautiful, effective code written both ways. Good code is good code, however you write it.
In general, you'll use C features for numerical calculations. You'll generally use objects for most other things. The reason for this is that objects are way heavier than a simple scalar — there's just no benefit to it. Why would you ever write [[NSNumber numberWithInteger:1] numberByAddingNumber:[NSNumber numberWithInteger:2]] when you can just write 1+2? It's not only painful to read, it's far slower and it doesn't gain you anything.
On the other hand, Cocoa has rich object libraries for strings, arrays, networking and many other areas, and using those is a big win.
Knowing what's there — and thus what the easiest way to do something is — is just a matter of learning. If you think something should be there and you can't find it, you can ask either here or on Apple's Cocoa-Dev mailing list.
As for a collection protocol — there really isn't one. The closest thing to it is the NSFastEnumeration protocol, which defines precisely one method: countByEnumeratingWithState:objects:count:. This lets you use the for (id someObject in someCollection) syntax to enumerate the objects in a collection. Otherwise, all the collections define their own independent interfaces.
The first problem I've encountered is that I don't know where to draw a line between ObjC and C.
My rule is to use C wherever it makes sense to you. Objective-C has the benefit of letting you choose when to be procedural and when to be object-oriented. Go with what fits best with the code you're writing.
Another thing that I couldn't find was a collection's protocol [...] I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Java) or I gotta check by hand every collection and see if there is a method that my collection should have.
Unlike Java, Objective-C does not have a master protocol for collections like the java.util.Collection interface. Also, there aren't a proliferation of specific container implementations as in Java. However, that gives you the freedom to implement a collection in a way that makes sense for your code.
For building a tree-like structure, you might take a look at NSTreeNode to see if it might be useful to leverage. (It may be more than you're need or want, but might be worth a shot.)
As far as rolling your own collection, I've learned a lot while creating CHDataStructures.framework, and you're welcome to use whatever you like from that code, or just look at my attempts at creating Cocoa-like structures, designed to complement the Foundation collections and operate similarly. Good luck!
Try to use each language for what it's good at. IMHO, this would include Obj-C objects but C-like code implementing methods. So use math.h and concise C code to implement logic, but don't be shy about using Obj-C classes to organize your larger blocks of functionality into something that makes sense.
Also, try to interact with the frameworks using their style so you're not running upstream.
As has been mentioned, there’s no real protocol for abstract collection classes (aside from the NSFastEnumeration protocol which provides the for(id item in collection) syntax when implemented), but there are conventions to follow.
Apple’s Introduction to Coding Guidelines for Cocoa covers some of this, and there is in fact a section on naming collection methods which covers the general cases (though note that generic container classes such as NSArray use the term “Object” as opposed to “Element” listed in the examples there – i.e. addObject:, removeObject:, and so on).
Following the patterns listed here (among others) is actually crucial when you want your classes to be KVC-compliant, which allows other users to observe changes in your object’s properties.