views:

947

answers:

2

Whats the difference between:

@interface SomeClass : NSObject {
    NSObject *something;
}

and

@interface SomeClass : NSObject {

}
NSObject *something;

? Also, what's the difference between Java's final and Objective C (C)'s const? And where should I declare static class members for the following situations: 1. When only the class needs it 2.Where it would be a property that other classes could read ? I already know about #define, but that isn't good for objects because it creates new ones each time. Thanks!

+2  A: 

As to the "final vs const" question, both are similar. They state that the value cannot change. note that in Java, as all values (except primitives) are pointers, the object it is pointing to could change underneath, but the memory location (the pointer) will never change. I believe you would expect similar behavior in Objective C, and it is always a good idea to not allow elements that are mutable be "final" or "const" as the values inside the object can still be modified then.

aperkins
outis
Thank you for clarifying that - I always confuse the special cases :)
aperkins
If you think that's confusing, check out: http://www.strainu.ro/programming/c/a-little-fun-with-cdecl/
outis
+5  A: 

The former is an instance variable and creates a something for each instance of SomeClass. It's similar to C's

typedef struct {
    NSObject *something;
} SomeClass;

The latter declares a global variable that has no real association with SomeClass. In C, it's equivalent to

NSObject *something;

defined in global scope. Objective-C doesn't really have class variables, so global variables are used (rather, are sometimes used; variables with compilation unit scope and static storage class are what should be used).

The cleanest way of defining a "class" variable is to define a static variable in the implementation file. That way, only the class methods can access it and you avoid polluting the global namespace. If you want it publicly available, define accessors.

Destroying class variables properly can be tricky. Memory will be reclaimed and open files will be closed automatically when the application exits, but other resources may not be handled so well.

outis