ios 自定义对象(赋值,指针引用问题)

问题:

自定义对象

#import <Foundation/Foundation.h>

@interface SensorInfo : NSObject
{
    NSString *m_strSersonNumber;            //传感器编号
    NSString *m_strSersonName;              //传感器名称
    NSString *m_strSceneModelStatus;        //传感器状态
    NSString *m_strSceneModelIndex;         //传感器所属模式
}

@property(retain, nonatomic) NSString *m_strSersonNumber;
@property(retain, nonatomic) NSString *m_strSersonName; 
@property(retain, nonatomic) NSString *m_strSceneModelStatus;
@property(retain, nonatomic) NSString *m_strSceneModelIndex;

@end

//.m文件
#import "SensorInfo.h"

@implementation SensorInfo

@synthesize m_strSersonName;
@synthesize m_strSersonNumber;
@synthesize m_strSceneModelStatus;
@synthesize m_strSceneModelIndex;

-(id)init
{
    self=[super init];
    if (!self)return nil;
    
    return self;
}

- (void)dealloc
{
    [m_strSersonName release];
    [m_strSersonNumber release];
    [m_strSceneModelStatus release];
    [m_strSceneModelIndex release];
    [super dealloc];
}

1,当A页面(SensorInfo) ----传递----B页面

2,B页面中修改SensorInfo

3,返回A页面的时候,SensorInfo也跟着被修改了   why?B页面中是all init的

解析:打印A,B中的SensorInfo会发现,指针地址是相同的,那么为什么all init之后还是相同指针地址呢!!默认是copy

在SensorInfo中添加函数

- (instancetype)initWithSensorInfo:(SensorInfo *)sensorInfo;
- (instancetype)initWithSensorInfo:(SensorInfo *)sensorInfo
{
    self=[super init];
    if (self)
    {
        self.m_strSceneModelIndex = sensorInfo.m_strSceneModelIndex;
        self.m_strSersonName =sensorInfo.m_strSersonName;
        self.m_strSersonNumber =sensorInfo.m_strSersonNumber;
        self.m_strSceneModelStatus =sensorInfo.m_strSceneModelStatus;
        return self;
    }
    
    return self;
}

B页面在取值的时候可以使用

SensorInfo *sensor = [[SensorInfo alloc] initWithSensorInfo:sensor]; 

而不是使用

SensorInfo *sensor = [mutArrSersonDevices objectAtIndex:i];

修改修改试试~还有不明白欢迎讨论

posted @ 2013-10-21 15:38  暖流  阅读(3003)  评论(0编辑  收藏  举报