2016-12-20 63 views
1

我在頭文件中創建了常量多維數組。我想從實現中訪問數組。怎麼做?如何訪問目標c中頭文件中定義的常量數組?

的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 
+0

你試過記錄它嗎?的NSLog( 「%@」,SORT_OPTIONS)? – Joshua

+0

這是沒用的... – hkaraoglu

+0

我其實已經試過了,它的工作原理: – Joshua

回答

1

我覺得有什麼不對您的定義。

#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" ]] 

子數組不包含@文字和您的@Product Name缺少"

嘗試是這樣的:

#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" ]] 

訪問它:SORT_OPTIONS[0]; // directly accessing the index

+0

它不起作用。它給了我這樣的錯誤:預期標識符 – hkaraoglu

+0

對不起。在每個元素之前沒有看到@符號。我添加了它。我訪問數組作爲SORT_OPTIONS [0]。謝謝。 – hkaraoglu

2

嘗試以下方法訪問你的常量數組,

在#進口之後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" ]] 

在.m文件後,

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

訪問陣列元素,

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

見附加的圖像,

.h file

.m file

希望它會幫助你。

+0

也謝謝你的幫助 – hkaraoglu

相關問題