objective-C:为什么接å£ç±»åž‹ä¸èƒ½é™æ€åˆ†é…?

时间:2014-11-17 16:32:06

标签: objective-c interface

NSString s1;   //compile error: interface type cannot be statically allocated
NSString *s2   //good

é™æ€æ„味ç€è¯¥å¯¹è±¡çš„内存是在编译时分é…çš„å—?但是在è¿è¡Œæ—¶åˆ†é…所有对象并通过指针访问的原因是什么? 我知é“指针å…许更好地使用内存,例如将它们作为方法的å‚数传递,但为什么ç¦æ­¢é™æ€åˆ†é…?我是这ç§è¯­è¨€çš„新手,我想了解它的愿景。

2 个答案:

答案 0 :(得分:5)

在C ++中,除éžæœ‰æŒ‡å‘该对象的指针,å¦åˆ™ä¸èƒ½æ‹¥æœ‰å¤šæ€å¯¹è±¡ã€‚ Objective-Cä¸å…许你打开那些蠕虫。它是一ç§åŠ¨æ€ç±»åž‹è¯­è¨€ï¼ˆå¦‚果你愿æ„,å¯ä»¥æ供很多ä¿æŠ¤ï¼‰ - 在编译时é”定你的类型è¿èƒŒäº†è¯­è¨€çš„哲学。

NSString *s2 = [[NSString alloc] initWith ???];

考虑那æ¡çº¿ã€‚你正在分é…一个字符串对象(我故æ„将构造函数的细节留空)。您将无法获得NSString的实际实例 - 您的对象类型将是ç§æœ‰å­ç±»ã€‚这个概念å«åšClass Clusters。

https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html

å–决于è¿è¡Œçš„构造函数以åŠä¼ å…¥çš„å‚æ•°å¯èƒ½ä¼šå½±å“è¿è¡Œæ—¶ç±»åž‹ã€‚对于é™æ€åˆ†é…的对象,这是ä¸å¯èƒ½çš„。

当然,你的问题还有很多,但考虑到æ¯ä¸ªå¯¹è±¡åœ¨è¿è¡Œæ—¶éƒ½æ˜¯åŠ¨æ€çš„,所有这些都是å¯èƒ½çš„。还è¦è€ƒè™‘è¿™é¿å…了C ++çš„å¤æ‚性。

答案 1 :(得分:1)

我对Objective-C有所了解。 (指针世界)。

     // In Objective C, you work with pointers. And In fact you cast them in order to help the compiler help you.

NSString *s1;  // This means: hey compiler I expect s1 points to a NSString.
id s2; // id is the same like (anyKind *), It´s a pointer to an object, no matter how what kind.

// s1 and s2 are in fact the same;

// Try this:
NSArray *array = @[@"Understanding",@"Objective C"];

s2 = array;

s1 = s2;

NSLog(@"Let´s go to see s2 store object: %@",[s2 description]);


NSLog(@"Let´s go to see s1 store object: %@",[s1 description]);

// All work, because the type you declare is in order to help the compiler, this doesn´t have any effect a runtime.
// In fact, object has problem a runtime, If they receive a selector (methods) what they don´t know. In this case
// the selector sended is knowing for all kind of objects.

// If you change the order and assign first s1, the compiler could help you, and a warning there will be.
// Tomorrow more.