hkaraoglu
hkaraoglu

Reputation: 1345

How to access defined constant array in header file in objective c?

I created constant multi dimensionel array in header file. I want to access array from implementation. How to do it?

Config.h

 #define SORT_OPTIONS @[ \
        [ @3, @"Default", @"&sort=p.sort_order&order=ASC" ],  \
        [ @1, @"Product Name (A - Z)", @"&sort=pd.name&order=ASC" ],  \
        [ @2, @"Product Name (Z - A)", @"&sort=pd.name&order=DESC" ], \
        [ @3, @"Low price > High price", @"&sort=p.price&order=ASC" ],  \
        [ @3, @"High price > Low price", @"&sort=p.price&order=DESC" ]]

Config.m

#import "Config.h"

@implementation Config

+ (void) initSortOptionsAsSortObject{
     // I want access array from here   
}

@end

Upvotes: 1

Views: 221

Answers (2)

KAR
KAR

Reputation: 3361

try following way to access your constant array,

In .h file after #import,

#define SORT_OPTIONS @[ \
@[ @3, @"Default", @"&sort=p.sort_order&order=ASC" ],  \
@[ @1, @"Product Name (A - Z)", @"&sort=pd.name&order=ASC" ],  \
@[ @2, @"Product Name (Z - A)", @"&sort=pd.name&order=DESC" ], \
@[ @3, @"Low price > High price", @"&sort=p.price&order=ASC" ],  \
@[ @3, @"High price > Low price", @"&sort=p.price&order=DESC" ]]

After in .m file,

+ (void) initSortOptionsAsSortObject{
    // I want access array from here
    NSLog(@"your array - %@", SORT_OPTIONS);
}

Access array elements,

for (int i = 0; i < SORT_OPTIONS.count; i++) {
        NSLog(@"your array - %@", [SORT_OPTIONS objectAtIndex:i]);
    }

See the attached images,

.h file

.m file

Hope It will help you.

Upvotes: 2

Joshua
Joshua

Reputation: 2451

I Think there is something wrong with your definition.

#define SORT_OPTIONS @[ \
    [ @3, @"Default", @"&sort=p.sort_order&order=ASC" ],  \
    [ @1, @Product Name (A - Z)", @"&sort=pd.name&order=ASC" ],  \
    [ @2, @"Product Name (Z - A)", @"&sort=pd.name&order=DESC" ], \
    [ @3, @"Low price > High price", @"&sort=p.price&order=ASC" ],  \
    [ @3, @"High price > Low price", @"&sort=p.price&order=DESC" ]]

the sub array does not contain @ literal and your @Product Name is missing a "

try it something like this:

#define SORT_OPTIONS @[ \
@[ @3, @"Default", @"&sort=p.sort_order&order=ASC" ],  \
@[ @1, @"Product Name (A - Z)", @"&sort=pd.name&order=ASC" ],  \
@[ @2, @"Product Name (Z - A)", @"&sort=pd.name&order=DESC" ], \
@[ @3, @"Low price > High price", @"&sort=p.price&order=ASC" ],  \
@[ @3, @"High price > Low price", @"&sort=p.price&order=DESC" ]]

Accessing it: SORT_OPTIONS[0]; // directly accessing the index

Upvotes: 1

Related Questions