Reputation: 5463
i was wondering how to access "static" vars from a model from different ViewControllers. Should I go for:
#import "CategoryModel.h"
@implementation CategoryModel
-(NSArray*) allSelected {
return [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SELECTEDCATEGORIES_DEFAULTSKEY]];
}
-(NSString*) allSelectedAsUrlParams {
NSMutableString *categoryList = [NSMutableString string];
for (NSArray *category in self.allSelected) {
[categoryList appendString:[category valueForKey:@"value"]];
if(![[self.allSelected lastObject] isEqual:category]) {
[categoryList appendString:@","];
}
}
return categoryList;
}
@end
*Edit (working) *
// header
#import <Foundation/Foundation.h>
@interface CategoryModel : NSObject
+ (NSString*)allSelectedAsUrlParams;
@end
// implementation
#import "CategoryModel.h"
@implementation CategoryModel
+ (NSString*)allSelectedAsUrlParams {
return @"somethingGreat";
}
@end
// How to use
CategoryModel.allSelectedAsUrlParams
Upvotes: 0
Views: 61
Reputation: 1945
This is really going to be a matter of architectural preference, but if more than one class is going to need the static vars, this is one approach:
Constants.h
extern BOOL const TEST_MODE;
extern NSString * const SOME_STRING;
Constants.m
BOOL const TEST_MODE = YES;
NSString * const SOME_STRING = @"SomeString";
As an alternative, you can just add the extern NSString * const SOME_STRING;
to the header of class that it is specific to (and the corresponding NSString * const SOME_STRING = @"SomeString";
in the .m) and then call that var directly by importing the header of the class with the constant you need and using SOME_STRING
to get at it.
Upvotes: 1