2015-02-12 66 views
3

我新的目标CObjective-C是否禁止使用结构?

我试图用一个简单的struct并得到

arc forbids objective-c objects in struct 

Looking up ARC,看起来这是一个定义目标C syntaxt规范 - 是正确的?

其次,如果不允许使用struct,我该怎么办?

谢谢!

编辑:一些代码作为样品

@implementation Cities { 
    // The goal is to have a struct that holds information about a city, 
    // like when a person started and ended living there. 
    // I was trying to make this struct an instance variable of the Cities 
    // class 
    // XCode doesn't like the below struct definition 

    struct City 
    { 
     NSString *name; 
     int *_startYear; 
     int *_endYear; 
    }; 
} 
+0

显示代码,为什么你想要一个结构? – Wain 2015-02-12 07:39:11

+0

现在没有什么特别的原因,我只是玩弄代码示例,并想知道为什么当使用'struct'的时候出现上述错误。如果不宜采用,那很好,我不会长期使用它。我更感兴趣的是为什么它抛出那个错误。谢谢! – user2490003 2015-02-12 07:43:26

+0

我不记得确切的原因,你可以使用结构只是不要把类指针放在它们中。 – Wain 2015-02-12 07:45:17

回答

8

弧禁止Objective-C对象在结构

结构是一个C构建体。编译器用非常明确的术语告诉你,在一个结构中你不能有Objective-C对象,而不是结构是非法的。

你可以使用所有你想要的常规C结构。

您的示例尝试将对Objective-C对象NSString的引用放入与ARC不兼容的struct中。

结构通常用于简单的数据结构。您很可能在Objective-C代码中遇到的示例是CGPointCGRect

CGPoint看起来像这样

struct CGPoint 
{ 
    CGFloat x; 
    CGFloat y; 
}; 

一个CGFloat是,我认为,只是一个double,并知道它代表的二维空间中的点。结构体可以包含指向其他结构体,C数组和C标准数据类型的指针,如int,char,float ...而Objective-C类可以包含结构体,但反过来不起作用。

结构也可能变得非常复杂,但这是一个非常广泛的话题,最好使用Google进行研究。

+0

注意详细说明常规C结构是什么?我不熟悉C以及:)我没有添加一个代码片段,但是,如果这有助于看到我正在尝试做什么。谢谢! – user2490003 2015-02-12 07:51:33

+0

这很有道理!还有一件事 - 对于在这里密集感到抱歉 - 我得到Objective C对象不能在结构中,所以我的NSString定义是无效的。但是你的结构包含CGFloat - 是不是Objective C对象? – user2490003 2015-02-13 20:50:51

+0

CGFloat只是float_32的一个typedef,我认为,不确定 – Bhargav 2016-08-10 10:48:41

8

在任何情况下,您都可以使用struct中的Objective-C++

#import <Foundation/Foundation.h> 

@interface City : NSObject 
struct Data { 
    NSString *name; 
}; 

@property struct Data data; 
@end 

@implementation City 
@end 

int main() 
{ 
    City *city = [[City alloc] init]; 
    city.data = (struct Data){@"San Francisco"}; 
    NSLog(@"%@", city.data.name); 
    return 0; 
} 

如果您将它编译为Objective-C,则说明您失败。

$ clang -x objective-c -fobjc-arc a.m -framework Foundation 
a.m:5:15: error: ARC forbids Objective-C objects in struct 
    NSString *name; 
      ^
1 error generated. 

因为C结构不具有管理的变量寿命的能力。

但是在C++中,struct确实具有析构函数。所以C++结构与ARC兼容。

$ clang++ -x objective-c++ -fobjc-arc a.m -framework Foundation 
$ ./a.out 
San Francisco 
1

如果要在Objective C中使用结构(使用ARC),请使用“__unsafe_unretained”属性。

struct Address { 
    __unsafe_unretained NSString *city; 
    __unsafe_unretained NSString *state; 
    __unsafe_unretained NSString *locality; 
}; 
相关问题