Go Back   MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Reply
 
Thread Tools Search this Thread Display Modes
Old Nov 9, 2010, 05:37 AM   #1
SanderDeclerck
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Just starting out at Objective-C, few noob questions

For now, I only got one question, but i'm pretty sure I'll be having a few more in the next couple of days, and I don't want to open a new topic for each of my noob questions :-).

So, I just started programming in Objective-C (just bought the book "Learn Objective-C on the Mac"), but I do have some experience programming in windows (vb, c# and java). So my first question really comes from that background.

In c# and java, for instance, you can have a list of objects from a specific type (called generics):
C#:
Code:
List<Rectangle> rectangles = new List<Rectangle>();
Java:
Code:
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
Is it correct to say that the NSMutableArray is the equivalent for the List in c# and the ArrayList in java, and is there a way to use generics (or any way to specify the object type for the elements in an array) in Objective-C?
SanderDeclerck is offline   0 Reply With Quote
Old Nov 9, 2010, 05:43 AM   #2
Menge
macrumors 6502a
 
Menge's Avatar
 
Join Date: Dec 2008
Location: Brazil
There's no genetics or templates in Objective-C. The NSArray or NSMutableArray class holds any kind of Objective-C instances except that the Mutable variant is... Mutable.
__________________
Menge - 2011 2.3GHz 13" MBP - 16GB iPhone 5 - 32GB iPad WiFi+4G - 8GB iPod Nano - AEBS
Menge is offline   0 Reply With Quote
Old Nov 9, 2010, 06:50 AM   #3
whooleytoo
macrumors 603
 
whooleytoo's Avatar
 
Join Date: Aug 2002
Location: Cork, Ireland.
Send a message via AIM to whooleytoo
As said above, you can use NSArrays or NSDictionarys for collections of objects of varying classes. You can use "id" as the generic type.

If, for instance, you're iterating through an array of mixed objects and don't know what objects it contains, you can identify each one by using the className method; or you can use respondsToSelector: to verify if that object contains the required method before calling it.
__________________
Mac <- Macintosh <- McIntosh apples <- John McIntosh <- McIntosh surname <- "Mac an toshach" <- "Son of the Chief"
whooleytoo is offline   0 Reply With Quote
Old Nov 9, 2010, 06:51 AM   #4
MatthewF
macrumors newbie
 
Join Date: Jun 2010
And an example:
Code:
NSMutableArray* myArray = [NSMutableArray new]
//The object can be any Obj-C instance.
[myArray addObject: myObject];
MatthewF is offline   0 Reply With Quote
Old Nov 9, 2010, 07:01 AM   #5
gnasher729
macrumors G5
 
gnasher729's Avatar
 
Join Date: Nov 2005
Quote:
Originally Posted by Menge View Post
There's no genetics or templates in Objective-C. The NSArray or NSMutableArray class holds any kind of Objective-C instances except that the Mutable variant is... Mutable.
You can of course use Objective-C++ (just use a file name that ends in .mm), so you have C++ with Objective-C extensions instead of C with Objective-C extensions. Whether that is a good idea is another matter. In general it is best to forget what C++ does and "go with the flow" of Objective-C: Use NSArray* and NSMutableArray* to hold arrays of objects, or NSDictionary* or NSSet*, whatever is better.


Quote:
Originally Posted by MatthewF View Post
And an example:
Code:
NSMutableArray* myArray = [NSMutableArray new]
//The object can be any Obj-C instance.
[myArray addObject: myObject];
I'd suggest you use the alloc/init pattern instead:

Code:
NSMutableArray* myArray = [[NSMutableArray alloc] init];
because it is much more flexible and is generally what everybody uses. (Makes it possible to use initialisers other then plain init).
gnasher729 is offline   0 Reply With Quote
Old Nov 9, 2010, 09:10 AM   #6
jared_kipe
macrumors 68030
 
jared_kipe's Avatar
 
Join Date: Dec 2003
Location: Seattle
Send a message via AIM to jared_kipe
Don't use NSObject's +new class method.

As gnasher has stated, Cocoa uses a two stage initialization with alloc/init, as well as designated initializers. This pattern is more robust and extensible.

The OTHER problem with +new is that it breaks Cocoa's own rules by returning a new object that is NOT autoreleased. Meaning that you own the object, and have to worry about releasing it when you are done.

Other Objective-C programmers will not like reading or debugging your code if you use +new for both of these reasons.

Code:
NSString *string = [NSString stringWithFormat: @"..."];  // autoreleased
NSNumber *num = [NSNumber numberWithDouble: 2.0]; // autoreleased
NSMutableArray *array1 = [NSMutableArray array]; // autoreleased
NSMutableArray *array2 = [NSMutableArray new]; // NOT autoreleased
[array1 addObject: string];
[array1 addObject: num];
[array2 addObject: string];
[array2 addObject: num];
//.....
return; // leaks an NSMutableArray, a NSString, a NSNumber
jared_kipe is offline   0 Reply With Quote
Old Nov 9, 2010, 09:25 AM   #7
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Something else I'd like to know is the following:

I'm still a student, in school we're seeing java and c#, not objective-c. So, if I study Objective-C on my own, I cant prove I can program in it. So, my question is: does Apple have some form of certification for developers?
SanderDeclerck is offline   0 Reply With Quote
Old Nov 9, 2010, 09:29 AM   #8
lee1210
macrumors 68040
 
lee1210's Avatar
 
Join Date: Jan 2005
Location: Dallas, TX
Quote:
Originally Posted by SanderDeclerck View Post
Something else I'd like to know is the following:

I'm still a student, in school we're seeing java and c#, not objective-c. So, if I study Objective-C on my own, I cant prove I can program in it. So, my question is: does Apple have some form of certification for developers?
No, they don't. Even if they did, certs prove nothing. Write some things in Objective-C. Have it available to an interviewer on a USB stick.

-Lee
lee1210 is offline   0 Reply With Quote
Old Nov 9, 2010, 09:36 AM   #9
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Quote:
Originally Posted by lee1210 View Post
No, they don't. Even if they did, certs prove nothing. Write some things in Objective-C. Have it available to an interviewer on a USB stick.

-Lee
That's a pity. I mean, you're completely right when saying they don't prove anything, but it can be the ticket to get the interview.
SanderDeclerck is offline   0 Reply With Quote
Old Nov 9, 2010, 11:36 AM   #10
chown33
macrumors 603
 
Join Date: Aug 2009
Quote:
Originally Posted by jared_kipe View Post
The OTHER problem with +new is that it breaks Cocoa's own rules by returning a new object that is NOT autoreleased.
This is incorrect because the rule is:
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. ((Bold added for emphasis.))
http://developer.apple.com/library/m...00994-BAJHFBGH
chown33 is offline   0 Reply With Quote
Old Nov 9, 2010, 12:17 PM   #11
Littleodie914
macrumors 68000
 
Littleodie914's Avatar
 
Join Date: Jun 2004
Location: Rochester, NY
Quote:
Originally Posted by jared_kipe View Post
Don't use NSObject's +new class method.

As gnasher has stated, Cocoa uses a two stage initialization with alloc/init, as well as designated initializers. This pattern is more robust and extensible.

The OTHER problem with +new is that it breaks Cocoa's own rules by returning a new object that is NOT autoreleased. Meaning that you own the object, and have to worry about releasing it when you are done.

Other Objective-C programmers will not like reading or debugging your code if you use +new for both of these reasons.

Code:
NSString *string = [NSString stringWithFormat: @"..."];  // autoreleased
NSNumber *num = [NSNumber numberWithDouble: 2.0]; // autoreleased
NSMutableArray *array1 = [NSMutableArray array]; // autoreleased
NSMutableArray *array2 = [NSMutableArray new]; // NOT autoreleased
[array1 addObject: string];
[array1 addObject: num];
[array2 addObject: string];
[array2 addObject: num];
//.....
return; // leaks an NSMutableArray, a NSString, a NSNumber
I'm afraid that the leaks in your example would be blamed on programmer error. The [... new] method is analogous to [[... alloc] init], and when you instantiate an object using [... new], you're responsible for releasing it:

Code:
SomeClass *instance = [[SomeClass alloc] init];
[instance methodCall];
[instance release]; // Correct, no leak.

instance = [SomeClass new];
[instance methodCall];
[instance release]; // Also correct, no leak.
If you were planning on using [[... alloc] init], you can use [... new], though it is "going out of style."
Littleodie914 is offline   0 Reply With Quote
Old Nov 9, 2010, 01:32 PM   #12
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Ok, I just read the chapter on memory management, 1 thing isn't quite clear: when do we use garbage collection, and when not? I mean when we're programming for mac os x 10.5 and later, do we just always use garbage collection, or are there cases we're just using the "retain-release"-method?
SanderDeclerck is offline   0 Reply With Quote
Old Nov 9, 2010, 01:39 PM   #13
lee1210
macrumors 68040
 
lee1210's Avatar
 
Join Date: Jan 2005
Location: Dallas, TX
Quote:
Originally Posted by SanderDeclerck View Post
Ok, I just read the chapter on memory management, 1 thing isn't quite clear: when do we use garbage collection, and when not? I mean when we're programming for mac os x 10.5 and later, do we just always use garbage collection, or are there cases we're just using the "retain-release"-method?
Will you ever target at or below 10.4? Will you ever want to re-use this code on iOS? Do you have strict memory needs that are important for you to handle yourself to avoid huge bloat/swapping/etc.? The answers to these will determine what the "right thing" to do is.

10.4 and below can't use GC, and iOS doesn't support GC. With GC on you're leaving it to a magical entity outside of your control to free memory. Maybe it will never free it. Who knows?

Also, with GC in any language it's possible for you to "leak" references to an Object. It's not a true leak, because if it's outside of the object graph it will get GC'd, but you could have a reference that you forget about that results in an Object never getting GC'd. It's just something to look out for, and I mention it because i feel like when you read about GC it seems magic and "for free", when it really isn't.

-Lee
lee1210 is offline   0 Reply With Quote
Old Nov 9, 2010, 02:18 PM   #14
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Thanks for all those responses, i really appreciate it.

Another question (i'm really sorry, but i'll keep asking questions):
When you start typing "if" in Xcode, it adds code completions as follows:
Code:
if (condition) {
    statements
}
However, I like my "{" at the beginning of the next line, like this:
Code:
if (condition)
{
    statements
}
Is there a way to change that?

Last edited by kainjow; Nov 9, 2010 at 03:31 PM. Reason: fixed formatting
SanderDeclerck is offline   0 Reply With Quote
Old Nov 9, 2010, 07:29 PM   #15
jared_kipe
macrumors 68030
 
jared_kipe's Avatar
 
Join Date: Dec 2003
Location: Seattle
Send a message via AIM to jared_kipe
Quote:
Originally Posted by Littleodie914 View Post
I'm afraid that the leaks in your example would be blamed on programmer error. The [... new] method is analogous to [[... alloc] init], and when you instantiate an object using [... new], you're responsible for releasing it:

Code:
SomeClass *instance = [[SomeClass alloc] init];
[instance methodCall];
[instance release]; // Correct, no leak.

instance = [SomeClass new];
[instance methodCall];
[instance release]; // Also correct, no leak.
If you were planning on using [[... alloc] init], you can use [... new], though it is "going out of style."
Lets back up a bit. I'm not saying that it literally leaks, or literally breaks Cocoa's rules for returned objects. I'm saying from an end user's (programmers) standpoint it does.

It makes it harder spot mistakes and leaks (isn't every leak a mistake??). It prevents you from using a designated initializer other than init, it prevents you from calling +allocWithZone: (which alloc calls on its own).
jared_kipe is offline   0 Reply With Quote
Old Nov 9, 2010, 07:31 PM   #16
jared_kipe
macrumors 68030
 
jared_kipe's Avatar
 
Join Date: Dec 2003
Location: Seattle
Send a message via AIM to jared_kipe
Quote:
Originally Posted by SanderDeclerck View Post
Ok, I just read the chapter on memory management, 1 thing isn't quite clear: when do we use garbage collection, and when not? I mean when we're programming for mac os x 10.5 and later, do we just always use garbage collection, or are there cases we're just using the "retain-release"-method?
I never use garbage collection. Honestly, retain-release is very easy to use properly.
jared_kipe is offline   0 Reply With Quote
Old Nov 9, 2010, 07:57 PM   #17
Bernard SG
macrumors 65816
 
Bernard SG's Avatar
 
Join Date: Jul 2010
Quote:
Originally Posted by SanderDeclerck View Post
Thanks for all those responses, i really appreciate it.

Another question (i'm really sorry, but i'll keep asking questions):
When you start typing "if" in Xcode, it adds code completions as follows:
Code:
if (condition) {
    statements
}
However, I like my "{" at the beginning of the next line, like this:
Code:
if (condition)
{
    statements
}
Is there a way to change that?
Doesn't matter where you put the "{".
__________________
21" 2008 iMac, 13" MBP, 32Gb iPod Touch 4, 2002 eMac, iPod Touch 2 8GB, iPod Nano 1st gen, iPad 3 white 32 GB 3G, iPhone 5 16 GB. Uhmm... Fanboi!
Bernard SG is offline   0 Reply With Quote
Old Nov 10, 2010, 04:31 AM   #18
gnasher729
macrumors G5
 
gnasher729's Avatar
 
Join Date: Nov 2005
Quote:
Originally Posted by jared_kipe View Post
Lets back up a bit. I'm not saying that it literally leaks, or literally breaks Cocoa's rules for returned objects. I'm saying from an end user's (programmers) standpoint it does.

It makes it harder spot mistakes and leaks (isn't every leak a mistake??). It prevents you from using a designated initializer other than init, it prevents you from calling +allocWithZone: (which alloc calls on its own).
I think "new" was a misguided attempt to make C++ programmers more at home. Misguided because alloc + init is something very different from C++ new, once you get a bit deeper into things.
gnasher729 is offline   0 Reply With Quote
Old Nov 10, 2010, 05:49 AM   #19
whooleytoo
macrumors 603
 
whooleytoo's Avatar
 
Join Date: Aug 2002
Location: Cork, Ireland.
Send a message via AIM to whooleytoo
Quote:
Originally Posted by jared_kipe View Post
Lets back up a bit. I'm not saying that it literally leaks, or literally breaks Cocoa's rules for returned objects. I'm saying from an end user's (programmers) standpoint it does.

It makes it harder spot mistakes and leaks (isn't every leak a mistake??). It prevents you from using a designated initializer other than init, it prevents you from calling +allocWithZone: (which alloc calls on its own).
It doesn't really make it much harder to spot mistakes. It's pretty easy, if you use the rough rule of thumb:

For every:
- new
- alloc
- copy
- retain

You need a:
- release
or
- autorelease

(and keep an eye on properties, which may have an implicit retain and release. One could argue - properties make it harder to spot leaks, more so than new!)
__________________
Mac <- Macintosh <- McIntosh apples <- John McIntosh <- McIntosh surname <- "Mac an toshach" <- "Son of the Chief"
whooleytoo is offline   0 Reply With Quote
Old Nov 11, 2010, 04:46 AM   #20
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
In java, when you make a setter, it's no problem to give the parameter the same name as the instance variable, because you can use this.variableName to set the instance variable, like this:
Code:
public void setName(String name)
{
this.name = name;
}
What would be the equivalent of this in ObjectiveC?
SanderDeclerck is offline   0 Reply With Quote
Old Nov 11, 2010, 07:01 AM   #21
Littleodie914
macrumors 68000
 
Littleodie914's Avatar
 
Join Date: Jun 2004
Location: Rochester, NY
Quote:
Originally Posted by SanderDeclerck View Post
In java, when you make a setter, it's no problem to give the parameter the same name as the instance variable, because you can use this.variableName to set the instance variable, like this:
Code:
public void setName(String name)
{
this.name = name;
}
What would be the equivalent of this in ObjectiveC?
There are a few different conventions. Since the name of the property you're setting is already in the method signature, for smaller methods like setters you can just use the first letter of the parameter:

Code:
- (void)setName:(NSString *)n {
    if (name != n) {
        if (name) {
            [name release];
        }
        name = [n copy];
    }
}
Alternatively, for larger methods (where it would be easy to lose a single-letter variable), you'll occasionally see the prefix 'a' in front of the variable names:

Code:
- (void)showEditWindow:(NSWindow *)aWindow withTitle:(NSString *)aTitle {
    ... // Code
}
Edit: Also, I'm surprised no one has mentioned CocoaDevCentral yet. One of the best sites out there for beginning and advanced Objective-C/Cocoa tutorials. Link

Last edited by Littleodie914; Nov 11, 2010 at 07:07 AM. Reason: Added CocoaDevCentral link.
Littleodie914 is offline   0 Reply With Quote
Old Nov 11, 2010, 09:38 AM   #22
whooleytoo
macrumors 603
 
whooleytoo's Avatar
 
Join Date: Aug 2002
Location: Cork, Ireland.
Send a message via AIM to whooleytoo
Quote:
Originally Posted by SanderDeclerck View Post
In java, when you make a setter, it's no problem to give the parameter the same name as the instance variable, because you can use this.variableName to set the instance variable, like this:
Code:
public void setName(String name)
{
this.name = name;
}
What would be the equivalent of this in ObjectiveC?
Typically you'd use the following convention:

In your .h file:
NSString* employeeName;

In your .m file:
[self setEmployeeName: @"John Smith"];
NSString* theName = [self employeeName];

However, for getter/setter methods, you should look at properties. They might confuse you a little at first, but they are very useful.

In your .h file:
NSString* employeeName;
..
@property (nonatomic, retain) NSString* employeeName;

In your .m file:
@synthesize employeeName;
..
self.employeeName = @"John Smith";
NSString* theName = self.employeeName;
self.employeeName = nil;

Why use properties?
- You don't have to write lots of get & set accessors. The synthesize directive tells the compiler to generate the getter and setter methods. Even though you haven't written them in this sample, they are there. With the first (non property example) you'd have to write the setEmployeeName: and employeeName methods.

- If in C you write employee1.salary, that's reading the salary directly from an instance variable. Now, let's say the system becomes more comples, and you now need to call a method to calculate the salary. You have to rewrite every reference to "salary" to call that new method instead.

In Obj-C, you can simply slot in a new "getter" method, which does the calculations. And you don't have to change the calling code! employee1.salary will first call the getter method. So it works regardless of whether salary is a fixed number that you store or a more dynamic number that you need to calculate in a method.

I hope that helped rather than confused!
__________________
Mac <- Macintosh <- McIntosh apples <- John McIntosh <- McIntosh surname <- "Mac an toshach" <- "Son of the Chief"
whooleytoo is offline   0 Reply With Quote
Old Nov 11, 2010, 10:22 AM   #23
SanderDeclerck
Thread Starter
macrumors member
 
Join Date: Nov 2010
Location: Poelkapelle, Belgium
Send a message via Skype™ to SanderDeclerck
Again, thanks for the very helpful answers I've been getting in this topic!

@whooleytoo: apparently the next chapter I had to read in the book I bought ("Learn Objective-C on the Mac"), was titled: "Properties" :-).
SanderDeclerck is offline   0 Reply With Quote

Reply
MacRumors Forums > Apple Systems and Services > Programming > Mac Programming

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Similar Threads
thread Thread Starter Forum Replies Last Post
Noob Objective-C / Framework / AVFoundation question Golgafrincham Mac Programming 0 Jan 30, 2014 02:54 AM
Basic Objective-C Cocoa questions? cpuin Mac Programming 8 Jun 3, 2013 07:10 PM
Objective-C noob: EXC_BAD_ACCESS with simple print method? dancks Mac Programming 14 Apr 27, 2013 04:47 PM
Basic Objective-C Questions xShane Mac Programming 12 Mar 18, 2013 11:08 AM
BecomeAnXcoder : A free book for starting with Cocoa using Objective-C msaljaber iPhone/iPad Programming 0 Feb 7, 2013 05:30 AM

Forum Jump

All times are GMT -5. The time now is 03:14 AM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC