美文网首页
结构体作为成员变量

结构体作为成员变量

作者: SimpleSJ | 来源:发表于2018-11-01 16:37 被阅读0次

    注意: 在ARC环境下,在结构体中使用objc对象,必须使用_unsafe_unretained,这个是苹果的规定。

    //案例:人拥有一条狗,狗为结构体
    
    //Person类 .h
    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    typedef struct  {
        __unsafe_unretained NSString *name;
        NSString *name;
        int age;
        double height;
    } Dog;
    
    @interface Person : NSObject
    {
        @public
        __unsafe_unretained NSString *_name;
        Dog _dog;
        int _age;
    }
    -(void)say;
    @end
    
    NS_ASSUME_NONNULL_END
    
    //Person类 .m
    @implementation Person
    -(void)say{
        NSLog(@"my name is %@, age is %d ,my dog's name is %@,my dog's height is %f,my dog's age is %d",_name,_age,_dog.name,_dog.height,_dog.age);
    }
    @end
    
    //controller 中创建一个人对象
        Person *person = [Person new];
        person->_name = @"sj";
        person->_age = 25;
        Dog d = {.name = @"wc",.age = 3,.height = 0.66};
        person->_dog = d;
        [person say];
    //输出:
    my name is sj, age is 25 ,my dog's name is wc,my dog's height is 0.660000,my dog's age is 3
    

    相关文章

      网友评论

          本文标题:结构体作为成员变量

          本文链接:https://www.haomeiwen.com/subject/udkxxqtx.html