iphone,如何调用struct成员

时间:2011-09-19 09:03:46

标签: iphone struct

我的ManageMarketPacket.h有一个结构,如下所示:

#import <Foundation/Foundation.h>
typedef struct ORIGINAL_QUOTA_DATA_tag{
    unsigned short  id;
    unsigned char   exch;          
}ORIGINAL_QUOTA_DATA;
@end

并且在ManageMarketPacket.m中有一个打算获取id的函数:

- (unsigned short)getId:(NetWorkConnect*)netWokrConnect{
   //I want to get the id which have assigend in netWokrConnect.m  
   //I tried "return (netWokrConnect->oQuota).id; "is incorrect  
}

在我的NetWorkConnect.h中,我定义了struct:

#import <Foundation/Foundation.h>
#import "ManageMarketPacket.h"
@interface NetWorkConnect : NSObject{    
    ORIGINAL_QUOTA_DATA oQuota;    
}

在NetWorkConnect.m中,我在另一个文件中分配了oQuota.and,我调用函数getId;

2 个答案:

答案 0 :(得分:0)

为了实现这一目标,您需要更改一些内容。

  1. 首先,您需要更改结构,因为您使用的是变量名id,而id是一个保留的Objective-C关键字。我将其更改为identifier,您需要更改使用变量

    的任何方法
    typedef struct ORIGINAL_QUOTA_DATA_tag {
       unsigned short  identifier;
       unsigned char   exch;          
    } ORIGINAL_QUOTA_DATA;
    
  2. 在您的NetworkConnect类中,您需要为oQuota变量添加@property和@synthesize,以便您可以从其他类中访问它:

    NetworkConnect.h

    #import <Foundation/Foundation.h>
    #import "ManageMarketPacket.h"
    @interface NetWorkConnect : NSObject{    
        ORIGINAL_QUOTA_DATA oQuota;    
    }
    
    @property (readwrite, assign) ORIGINAL_QUOTA_DATA oQuota;
    

    NetworkConnect.m

    @implementation NetworkConnect
    @synthesize oQuota;
    
        // Rest of your Implementation here...
    
    @end
    
  3. 访问方法中的oQuota变量。你需要改变它:

    - (unsigned short)getId:(NetWorkConnect*)netWokrConnect{
         // I want to get the identifer which have assigend in netWokrConnect.m  
         netWokrConnect->oQuota.identifer;
    }
    

    或者你也可以使用.点语法,我喜欢这样:

    - (unsigned short)getId:(NetWorkConnect*)netWokrConnect{
         // I want to get the identifer which have assigend in netWokrConnect.m  
         netWokrConnect.oQuota.identifer;
    }
    

答案 1 :(得分:0)

首先,您必须从oQuota中创建一个属性,以使其在定义它的类之外可见。然后你可以这样简单地调用它:netWorkConnect.oQuota.id