开发者

What the difference between a.b and a->b in Objective C?

A requirement of A.B is that A must declare @synthesize before using the setter or getter but 开发者_StackOverflowA->B doesn't require this.

I don't understand which is better and what one uses the least amount of memory?

If I convert from A.B to A->B will it use less memory or the same amount? A->B uses less memory because you don't need to declare @synthesize, right?


If a is an Objective-C object then a.b = c; is the same as to write [a setB:c];.

setB: in this case is a default name for automatic generated setter method when you are specifying @property (...) typeB b; and @synthesize b. Instead of ... you can place corresponding memory specifier, as retain, assign, copy. By writing a->b = c you avoid using setter method, and access b directly.

So, construction a->b generates less extra-code but breaks one of the major OOP notion of "Encapsulation" and you also should handle memory related staff manually.

For example if you've specified retain in b's @property, then construction a.b = c will behave almost in the same fashion as a->b = [c retain].


Since your question is tagged C too, a->b and a.b access the same element (b) of the structure (a), but in the first case a is a pointer to a structure, while in the second a is a structure itself.


It's not a case of one being better than the other. They do different things.

If you declare a property (i.e., an @property and a @synthesize or @dynamic), then the compiler will generate getters and setters for you, both using the standard Objective-C naming conventions.

a->b is actually a C construct. It can be used in Objective-C but is much less common. Perhaps the easiest way to explain is with the following code:

typedef struct { int a; int b; } someType;

someType a;
someType* b;

// assign values 
a.a = 1;
a.b = 2;

// also assign values (assume memory has been allocated)
b->a = 1;
b->b = 2;

(This is from memory. There may be typos.)


a.b => member b of object a
a->b => member b of object pointed by a

In first memory to object a is allocated on stack. In the second case, memory for the object that a is pointing to is given from free store.

Note: Since your question tagged C++.


if a is a struct use a.b

if a is a pointer to a struct use a->b

if a is an object pointer and b is a ivar use a->b

if a is an object pointer and b is a property use a.b

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜