如何使用点表示法分配Objective-C属性?

时间:2014-12-08 16:07:50

标签: objective-c windows gnustep

我是Objective-C的新手。我目前正在使用以下代码测试属性。请注意,这是在使用GNUstep的Windows上:

#import <Foundation/Foundation.h>

@interface Car : NSObject
    @property NSString *color;
@end

@implementation Car
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Car *honda = [[Car alloc] init];
    honda.color = @"Red";
    NSLog(@"%s", honda.color);   

    [pool drain]; 
    return 0;
}

但是得到以下内容:

C:\Users\Bab\Desktop\main.m:5:2: warning: object property 'color' has no 'assign', 'retain' or 'copy' attribute; assuming 'assign' [enabled by default]
C:\Users\Bab\Desktop\main.m:5:2: note: 'assign' can be unsafe for Objective-C objects; please state explicitly if you need it
C:\Users\Bab\Desktop\main.m:9:1: warning: incomplete implementation of class 'Car' [enabled by default]
C:\Users\Bab\Desktop\main.m:9:1: warning: method definition for '-setColor:' not found [enabled by default]
C:\Users\Bab\Desktop\main.m:9:1: warning: method definition for '-color' not found [enabled by default]
: Uncaught exception NSInvalidArgumentException, reason: Car(instance) does not recognize setColor:
[Finished in 0.4s with exit code 1]

3 个答案:

答案 0 :(得分:2)

我不知道或关心Windows上的GNUStep。但我的猜测是,如果Windows上的GNUStep缺少ARC,它缺乏属性的自动合成。因此,您必须明确地说@synthesize,或者甚至编写自己的访问方法。

此处进一步讨论:http://wiki.gnustep.org/index.php/ObjC2_FAQ#Which_Bits_of_Objective-C_2_Work.3F

基本上似乎“现代运行时”的大部分可能不存在。

答案 1 :(得分:0)

如果您使用gcc在mac终端下编译这些代码,您可能会得到以下内容:

SinriMac:overstack Sinri$ gcc 03.m -framework Foundation
03.m:4:5: warning: no 'assign', 'retain', or 'copy' attribute is specified -
  'assign' is assumed [-Wobjc-property-no-attribute]
@property NSString *color;
^
03.m:4:5: warning: default property attribute 'assign' not appropriate for
  non-GC object [-Wobjc-property-no-attribute]
03.m:16:18: warning: format specifies type 'char *' but the argument has type
  'NSString *' [-Wformat]
NSLog(@"%s", honda.color);   
        ~~   ^~~~~~~~~~~
        %@
3 warnings generated.

SinriMac:overstack Sinri$ ./a.out
2014-12-09 00:16:55.804 a.out[86907:5686808] `踺u…
SinriMac:overstack Sinri$ 

所以它应该是GNUStep的问题。使用@synthesize是解决此问题的方法。

PS 无论如何,%s在这里很奇怪,为什么不使用%@

答案 2 :(得分:0)

问题不在于符号。问题出在这里:

: Uncaught exception NSInvalidArgumentException, reason: Car(instance) does not recognize setColor:

运行时正在寻找预期的&#34; setColor&#34;物业的访问者&#34;颜色&#34;。要自动生成访问器,请将@synthesize用作matt表示,或者在实现中明确创建它们。

合成说明: What exactly does @synthesize do?

但是,@synthesize是一个objective-c 2.0关键字,GNUStep中的gcc不支持。您需要使用clang来启用此功能:How can i use Objective-C's Property feature in GNUstep?

我在本指南中安装了clang:https://solarianprogrammer.com/2012/03/21/clang-objective-c-windows/

仅供参考这不是ARC问题 - ARC是objective-c的一部分,而不是 Fred Frith-MacDonald所说的GNUStep。 ARC也可以通过clang / llvm在GNUStep下使用。