-2

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
Hazem Abdullah
  • 1,837
  • 4
  • 23
  • 41
  • 1
    you do not initialize a property in the header do it in the implementation file specifically in the `init` method – Joshua Jan 20 '14 at 08:08

3 Answers3

4

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
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

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 ];
James Frost
  • 6,960
  • 1
  • 33
  • 42
  • 2
    And how to get the values in this way? – Hazem Abdullah Jan 20 '14 at 08:47
  • 1
    To retrieve values, you can access elements like you would a normal C array: `NSNumber *number = self.myArray[0];`. Note that if you want a primitive `NSInteger` value back (rather than an `NSNumber` object), you'll need to call `integerValue` on the number: `[number integerValue];`. – James Frost Jan 20 '14 at 09:15
0

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.

santhu
  • 4,796
  • 1
  • 21
  • 29