Objective-C Custom Class with Struct tutorial - objective-c

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.

Related

Setters/Getters at game programming?

I was reading the sources for LibGDX, and I saw that there are too many public fields inside classes. So I was wondering, why? Is there any advantage instead setting up the typical setters/getters for that fields?
I know I should avoid direct accessing to class' fields, but if a guy like the author of LibGDX do it, I'm starting to doubt about "what are the best practices".
You don't have to know the implementation of this class, so they make your code simpler. Also, you are sure some variables you do not want them to be changed adheres to the rules. So they make sure you don't mess up with your code.

subclassing classes in Cocoa

My question is : Why Apple prohibit some classes to be subclassed, for example MKMapView ?
What is the reason to do this please ?
thanks for your answers
The short answer is that although they look like normal classes, they probably aren't. This means that subclassing them without some knowledge of how they're implemented probably won't do what you're expecting.
There are some, like the collection classes, that you can subclass but you need to follow some documented rules. And there are others that they just say "don't." I've seen developers ignore this advice only to find that their app breaks on the next iOS update.
The good news is that the way that these classes are implemented usually means that if you're trying to subclass them you're probably doing it wrong. Cocoa heavily relies on delegates and composition, which means that you tend to subclass system components far less often than you would in other frameworks such as Java and .Net.

Making Objective-C Classes look Beautiful

I wanted to ask you all for you opinions on code smells in Objective C, specifically Cocoa Touch. I'm working on a fairly complex game, and about to start the Great December Refactoring.
A good number of my classes, the models in particular, are full of methods that deal with internal business logic; I'll be hiding these in a private category, in my war against massive header files. Those private categories contain a large number of declarations, and this makes me feel uneasy... almost like Objective-C's out to make me feel guilty about all of these methods.
The more I refactor (a good thing!), the more I have to maintain all this duplication (not so good). It just feels wrong.
In a language like Ruby, the community puts a LOT of emphasis on very short, clear, beautiful methods. My question is, for Objective C (Cocoa Touch specifically), how long are your methods, how big are your controllers, and how many methods per class do you all find becomes typical in your projects? Are there any particularly nice, beautiful examples of Classes made up of short methods in Objective C, or is that simply not an important part of the language's culture?
DISCLOSURE: I'm currently reading "The Little Schemer", which should explain my sadness, re: Objective C.
Beauty is subjective. For me, an Objective-C class is beautiful if it is readable (I know what it is supposed to do) and maintainable (I can see what parts are responsible for doing what). I also don't like to be thrown out of reading code by an unfamiliar idiom. Sort of like when you are reading a book and you read something that takes you out of the immersion and reminds you that you are reading.
You'll probably get lots of different, mutually exclusive advice, but here are my thoughts.
Nothing wrong with private methods being in a private category. That's what it is there for. If you don't like the declarations clogging up the file either use code folding in the IDE, or have your extensions as a category in a different file.
Group related methods together and mark them with #pragma mark statements
Whatever code layout you use, consistency is important. Take a few minutes and write your own guidelines (here are mine) so if you forget what you are supposed to be doing you have a reference.
The controller doesn't have to be the delegate and datasource you can always have other classes for these.
Use descriptive names for methods and properties. Yes, you may document them, but you can't see documentation when Xcode applies code completion, where well named methods and properties pay off. Also, code comments get stale if they aren't updated while the code itself changes.
Don't try and write clever code. You might think that it's better to chain a sequence of method calls on one line, but the compiler is better at optimising than you might think. It's okay to use temporary variables to hold values (mostly these are just pointers anyway, so relatively small) if it improves readability. Write code for humans to read.
DRY applies to Objective-C as much as other languages. Don't be worried about refactoring code into more methods. There is nothing wrong with having lots of methods as long as they are useful.
The very first thing I do even before implementing class or method is to ask: "How would I want to use this from the outside?"
I never ever, never begin by writing the internals of my classes and methods first. By starting of with an elegant public API the internals tend to become elegant for free, and if they don't then the ugliness is at least contained to a single method or class, and not allowed to pollute the rest of the code with it's smell.
There are many design patterns out there, two decades of coding have taught me that the only pattern that stand the test of time is: KISS. Keep It Simple Stupid.
Some general rules of thumb, for any language or environment:
Follow your gut feeling over any advice you have read or heard!
Bail out early!
If needed, verify inputs early and bail out fast! Less cleanup to do.
Never add something to your code that you do not use.
An option for "reverse" might feel like something nice to have down the road.
In that case add it down the road! Do not waste time adding complexity you do not need.
Method names should describe what is done, never how it is done.
Methods should be allowed to change their implementation without changing their name as long as the result is the same.
If you can not understand what a method does from it's name then change the name!
If the how part is complex enough, then use comments to describe your implementation.
Do not fear the singletons!
If your app only have one data model, then it is a singleton!
Passing around a single variable all over the place is just pretending it is something else but a singleton and adding complexity as bonus.
Plan for failures from the start.
Always use for doFoo:error instead of doFoo: from the start.
Create nice NSError instances with end user readable localized descriptions from the start.
It is a major pain to retrofit error handling/messages to a large existing app.
And there will always be errors if you have users and IO involved!
Cocoa/Objective-C is Object* Oriented, not **Class Oriented as most of the popular kids out there that claim to be OOP.
Do not introduce a dumb value class with only properties, a class without methods performing actual work could just as well be a struct.
Let your objects be intelligent! Why add a whole new FooParser class if a fooFromString: method on Foo is all you need?
In Cocoa what you can do is always more important than what you are.
Do not introduce a protocol if a target/action can do.
Do not verify that instances conforms to protocols, is a kind of class, that is up to the compiler.
My 2 cents:
Properties are usually better than old-style getter+setter. Even if you use #dynamic properties - declare them with #property, this is way more informative and shorter.
I personally don't simulate "private" methods for classes. Yes, I can write a category somewhere in the .m(m) file, but since Obj-C has no pure way to declare a private method - why should I invent one? Anyway, even if you really need something like that - declare a separate "MyClassPrivate.h" with a category and include it in the .m(m) files to avoid duplicating the declarations.
Binding. Binding for most Controller <-> UI relations, use transformers, formatters, just don't write methods to read/write controls values manually. It makes code look like something from MFC era.
C++, a lot of code look much better and shorter when written in C++. Since compiler understands C++ classes it's a good point for refactoring, especially when working will a low-level code.
I usually split big controllers. Something more than 500 lines of code is a good candidate for refactoring for me. For instance, I have a document window controller, since some version of the app it extends with image importing/exporting options. Controller grows up to 1.000 lines where 1/2 is the "image stuff". That's a "trigger" for me to make an ImageStuffController, instantiate it in the NIB and put all image-relative code in there.
All above make it easier for me to maintain my code. For a huge projects, where splitting the controllers and classes to keep 'em small results big number of files, I usually try to extract some code into a framework. For example, if a big part of the app is communicating with external web-services, there is usually a straight way to extract a MyWebServices.framework from the main app.

Too much C-Style in Objective-C programs?

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.

Objective-C newbie: Does anyone know of diagrams that explain class, objects and methods?

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.