0

Since I've started on iPhone development I've been kinda confused as to which is the best way to access data as a member in a Class.

Let's say I have a class called MyClass, and in it I have:

@interface MyClass : NSObject {
    int myInt;
}

@property (nonatomic, assign) int myInt;

In the implementation, is it better to do this:

myObject.myInt = 1;

Or this?

[myObject setMyInt:1];

This goes for reading the value too.

int newInt = myObject.myInt;

vs.

int newInt = [myObject myInt];
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dkaranovich
  • 729
  • 7
  • 21
  • 1
    Nearly an exact duplicate of http://stackoverflow.com/questions/1249392/ asked just 2 days prior. The answers to that question are more complete and helpful than those here, as well. It would be best to do a more complete search before asking, but 2 questions is better than 0 questions. :-) – Quinn Taylor Aug 11 '09 at 04:30

3 Answers3

8

It doesn't really matter, they are the same thing. The dot syntax is a convenience that's there for you to use, and I feel like it makes your code cleaner.

The one case where I find that using the dot syntax throws warning or errors from the compiler is if you have have an id object, even if you know it has that property.

id someReturnedObject = [somethingObject someMysteryObjectAtIndex:5];
int aValue = 0;
aValue = someReturnedObject.value; // warning
aValue = [someReturnedObject value]; // will just do it
Neil
  • 1,813
  • 1
  • 12
  • 20
2

The type of the object is statically checked with the . syntax, but not with the [] syntax. This means you can't use . if the object's type isn't specified, and that it is beneficial to use it when it is, so the compiler will help you more.

Drew Hoskins
  • 4,168
  • 20
  • 23
0

Dot syntax in Objective-C is essentially shorthand for using the accessor methods. The message is still sent via the accessor method. Hope that answers your question

CarbonX
  • 134
  • 6