In the header file I want to declare an array of NSInterger, what's the best way to do that? I try this code, but it lead to an error
@interface test:NSObject
{
}
@property(nonatomic,readwrite)NSInteger f[4]={1,2,3,4}; // Error!!!
@end
In the header file I want to declare an array of NSInterger, what's the best way to do that? I try this code, but it lead to an error
@interface test:NSObject
{
}
@property(nonatomic,readwrite)NSInteger f[4]={1,2,3,4}; // Error!!!
@end
You cannot do this; instead initialize the array in the object's init
method and provide a custom setter/getter:
Header:
@interface test:NSObject
{
NSInteger _f[4];
}
@property(nonatomic,readwrite) NSInteger *f;
@end
Implementation:
@implementation test
- (id)init {
self = [super init];
if (self) {
_f[0] = 1;
_f[1] = 2;
_f[2] = 3;
_f[3] = 4;
}
return self;
}
- (NSInteger *)f {
return _f;
}
- (void)setF:(NSInteger *)f {
for (NSUInteger i = 0; i < 4; i++)
_f[i] = f[i];
}
@end
Are you sure you want an array of NSIntegers? NSIntegers are a primitive type; they are not objects. The usual convention in Objective-C for most use cases would be to store an NSArray of NSNumber objects. A literal number can be converted into an NSNumber by prefixing it with the @
symbol.
In your header:
@property(nonatomic, strong) NSArray *myArray;
In your init
method or similar:
self.myArray = @[ @1, @2, @3, @4 ];
int array[100]; create it as a global variable.
In your .m file add it after,
@interface MyClass ()
@end
@implementation MyClass{
}
int a[] ={1,2,34};
-(void)init{,.....
Try to NSLog(@"%d",a[1]), it will print perfectly.