开发者

Pointer to a property in singleton

NSMutableDictionary *searchFilters = [GlobalData instance].searchFilters;
if([searchFilters count] == 0)
{
    NSLog(@"no more keys, destroy global filters");

    [GlobalData instance].searchFilters = nil; // this is okay

    // searchFilters = nil; <-- this is not okay
}

Hi开发者_StackOverflow社区 guys, can someone help me to understand better pointers in Objective C? As shown above, I have a dictionary property stored in a singleton called 'GlobalData', using a pointer *searchFilters i can point to this dictionary and read its values correctly, but, if i want to MODIFY its value, code like 'searchFilters = nil' will not modify the value in the global singleton at all.

i need a shortcut to [GlobalData instance].searchFilters so that i do not need to retype "[GlobalData instance].searchFilters" each time... be it a pointer, pointer to pointer, watever, i want to know is there to wat to address that property in the singleton faster.


Your pointer searchFilters is pointing to the same location as [GlobalData instance].searchFilters, but it's not the same pointer, what you created is an alias.

So searchFilters = nil is assigning nil to the alias you created, the original pointer remains untouched.

This is the same behaviour as in C :)


You have two different pointers pointing to the same object. The fact that the object is a singleton makes no difference — they're different variables that just happen to share the same value. Similarly:

int a = 5;
int b = a;
b = 6;
printf("a = %d and b = %d", a, b); // Prints "a = 5 and b = 6

a and b are totally different variables independent from each other even though they both contained the value 5 initially.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜