BOOL bl = YES;
BOOL *bl_pointer = &bl;
*bl_pointer = NO;
NSLog(@"bl is %@", bl?@"YES": @"NO");
NSString *st;
st = @"ss";
NSLog(@"%@ is a string", st);
我最近在学习Objective-C并感到困惑:不应该是
*st = @"ss";
像
*bl_pointer = NO;
因为st也是一个指针,比如bl_pointer,或者我错过了什么?
“Objective-C中的所有变量都是指针”是什么意思?
答案 0 :(得分:1)
语句“Objective-C中的所有变量都是指针”是错误的。
所有objc对象都在堆上分配,并通过指针引用(这在技术上也是正确的,因为标记指针等等,但它足够好,直到你获得更好的理解)。
原生C类型(例如,整数类型和结构)将被视为在C中。
NSString
是一个客观的C对象。因此,你需要一个指针。
// This is a C type -- not an objc object.
BOOL bl = YES;
// This is a pointer to a BOOL, initialized to point to bl
BOOL *bl_pointer = &bl;
// Dereference a pointer to assign NO to what is being pointed to
*bl_pointer = NO;
// NSString is an objc object, and variables must be pointers
NSString *st;
// You are now pointing to a NSString with the value "ss"
// The confusion may be due to the @"" syntax, which just means that
// there is some NSString object, that has the value "ss" and it is
// being assigned to st. Note, you read about memory management as well.
st = @"ss";
我建议你得到一本很好的入门书,因为这些都是非常基本的问题。