所以我是一个 Flash 爱好者,我正在尝试将以下代码转换为对象 C:
var slot:Object = new Object();
slot.id = i;
slot.xPos = 25*i;
slot.yPos = 25*i;
slot.isEmpty = False;
// push object to array
arrGrid.push(slot);
稍后我可以重写:
arrGrid[0].isEmpty = True;
我似乎找不到在对象 C 中创建通用对象的引用。有人可以帮忙吗?
最佳答案
假设你正在 cocoa 中使用 iphone 或 mac 做一些事情,你可以简单地继承 NSObject(objective-c 中的基类)。
你需要一个 .h 和 .m,所以对于你的例子来说,它会是这样的: (注意,我使用slotId而不是id,因为id是objective-c中的关键字)
插槽.h
// Slot.h
@interface Slot : NSObject {
NSInteger slotId;
float xPos;
float yPos;
BOOL empty;
}
@property NSInteger slotId;
@property float xPos;
@property float yPos;
@property BOOL empty;
@end
// Slot.m
#import "Slot.h"
@implementation Slot
@synthesize slotId;
@synthesize xPos;
@synthesize yPos;
@synthesize empty;
@end
它定义了一个简单的 Slot 对象,具有 4 个属性,可以使用点表示法进行访问,例如:
s = [[Slot alloc] init];
s.empty = YES;
s.xPos = 1.0;
s.yPos = 1.0;
根据您处理的数据类型,您使用的数据类型以及定义属性的方式等有很多变化。
如果您想将槽对象添加到数组,请看一个简单的例子:
// create an array and add a slot object
NSMutableArray *arr = [NSMutableArray array];
Slot *slot = [[Slot alloc] init];
[arr addObject:slot];
// set the slot to empty
[[arr objectAtIndex:0] setEmpty:YES];
关于Iphone 对象 C - 数据、对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/866581/