Accessing typedef enum function in iPhone? - iphone

I am using to typedef with somevalues in the header. how can i access the enum values and used in the application any one help me.
typedef enum{
INFO,PROD,WARN
}INFOS;
#interface ViewController : UIViewController{
INFOS infos;
}
-(NSString *)method:(INFOS)infovalue;
- (void)viewDidLoad
{
[self method:infos];
[super viewDidLoad];
}
- (NSString *) method:(INFOS) infovalue {
NSString *result = nil;
switch(infovalue) {
case INFO:
result = #"info";
break;
case PROD:
result = #"prod";
break;
case WARN:
result = #"warn";
break;
default:
result = #"unknown";
}
return result;
}
but the method not called after the view load. how can i do it.pls help me

typedef enum{
info = 1,
prod = 2,
warn = 3
}INFOS;
#interface ViewController : UIViewController{
//INFOS infos; you do not need this
}
-(NSString *)method:(INFOS)infovalue;
-(void)viewDidLoad;
{
[self method:info];
[super viewDidLoad];
}
- (NSString *) method:(INFOS) infovalue {
NSString *result = nil;
switch(infovalue) {
case 1:
result = #"info";
break;
case 2:
result = #"prod";
break;
case 3:
result = #"warn";
break;
default:
result = #"unknown";
}
return result;
}

Related

Expected Expression iOS Xcode

I'm trying to make a simple Calculator App and I'm following instructions in this video ( https://www.youtube.com/watch?v=Uzq41DRC0-Q )
However, when i got to about 9:14, I got an error saying "Expected Expression" and some mark before the else statement. I cannot post images now, so post me everything you know, please. I'm a newbie, so any help would be appreciated!
My code (ViewController.m) :
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)ClearPressed:(id)sender {
}
- (IBAction)MinusPressed:(id)sender {
}
- (IBAction)PlusPressed:(id)sender {
}
- (IBAction)EqualsPressed:(id)sender {
}
- (IBAction)NumberPressed:(UIButton*)sender;{
NSInteger tag = sender.tag;
if (operatorPressed == FALSE) {
if (firstEntry == NULL) {
firstEntry = [NSString stringWithFormat:#"%li", (long)tag];
_OutputLabel.text = firstEntry;
}
}
else {
firstEntry = [NSString stringWithFormat:#"%#%li",firstEntry ,(long)tag];
_OutputLabel.text = firstEntry;
}
else { //HERE MY PROBLEM IS
if (secondEntry == NULL) {
secondEntry = [NSString stringWithFormat:#"%li", (long)tag];
_OutputLabel.text = secondEntry;
}
else {
if secondEntry = [NSString stringWithFormat:#"%#%li",firstEntry ,(long)tag];
_OutputLabel.text = secondEntry;
}
}
}
#end
You have two else statements. That's a no no.
- (IBAction)NumberPressed:(UIButton*)sender;{
NSInteger tag = sender.tag;
if (operatorPressed == FALSE) {
if (firstEntry == NULL) {
firstEntry = [NSString stringWithFormat:#"%li", (long)tag];
_OutputLabel.text = firstEntry;
}
}
else { // 1
firstEntry = [NSString stringWithFormat:#"%#%li",firstEntry ,(long)tag];
_OutputLabel.text = firstEntry;
}
else { // 2
if (secondEntry == NULL) {
secondEntry = [NSString stringWithFormat:#"%li", (long)tag];
_OutputLabel.text = secondEntry;
}
else {
if secondEntry = [NSString stringWithFormat:#"%#%li",firstEntry ,(long)tag];
_OutputLabel.text = secondEntry;
}
}
}
Check where I marked off with 1 and 2. The first else should be else if (someCondition). You can't have two else statements.

What alternatives to a switch statement could I use to update my UITableViewCells? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Alternative to switch statement in objective C
I have json data from an url which I display in the table cell using a switch statement. Since I have only 6 cells, I had used a switch statement but I am curious to know if there is any other method in place of switch statement to do so.
switch(indexPath.row)
{
case 0 :
cell.textLabel.text = [NSString stringWithFormat:#"%# %#",[dictionary valueForKey:#"firstname"],
[dictionary valueForKey:#"lastname"]];
break;
case 1:
cell.textLabel.text = [NSString stringWithFormat:#"%# : %#",#"Address",[dictionary valueForKey:#"address"]];
break;
case 2:
cell.textLabel.text = [NSString stringWithFormat:#"%# : %#",#"Age",[dictionary valueForKey:#"age"]];
break;
case 3:
cell.textLabel.text = [NSString stringWithFormat:#"%# : %#",#"Occupation",[dictionary valueForKey:#"occupation"]];
break;
case 4:
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [NSString stringWithFormat:#"%# : %#",#"Rating",[rate valueForKey:#"average"]];
break;
case 5:
cell.textLabel.text = [NSString stringWithFormat:#"%# : %#",#"Total Rating",[rate valueForKey:#"totalRatings"]];
break;
}
Here's a way to completely overengineer the problem, but you may find some useful nuggets in there which will help you with your specific problem:
typedef enum MONTableViewCellID {
MONTableViewCellID_Name = 0,
MONTableViewCellID_Address,
MONTableViewCellID_Age,
MONTableViewCellID_Occupation,
MONTableViewCellID_Rating,
MONTableViewCellID_TotalRating
} MONTableViewCellID;
#interface MONTableViewStuff : NSObject
{
#private
NSDictionary * dictionary;
NSDictionary * rate;
UITableViewCell * cell;
NSIndexPath * indexPath;
}
#end
#implementation MONTableViewStuff
- (UITableViewCellAccessoryType)tableViewAccessoryTypeForRow:(NSUInteger)row
{
if (MONTableViewCellID_Rating == row) {
return UITableViewCellAccessoryDisclosureIndicator;
}
return UITableViewCellAccessoryNone;
}
- (NSString *)lhsTextForRow:(NSUInteger)row
{
switch (row) {
case MONTableViewCellID_Name :
return [dictionary objectForKey:#"firstname"];
case MONTableViewCellID_Address :
return #"Address";
case MONTableViewCellID_Age :
return #"Age";
case MONTableViewCellID_Occupation :
return #"Occupation";
case MONTableViewCellID_Rating :
return #"Rating";
case MONTableViewCellID_TotalRating :
return #"Total Rating";
default : {
assert(0 && "invalid row");
return #"";
}
}
}
- (NSString *)rhsTextForRow:(NSUInteger)row
{
switch (row) {
case MONTableViewCellID_Name :
return [dictionary objectForKey:#"lastname"];
case MONTableViewCellID_Address :
return [dictionary objectForKey:#"address"];
case MONTableViewCellID_Age :
return [dictionary objectForKey:#"age"];
case MONTableViewCellID_Occupation :
return [dictionary objectForKey:#"occupation"];
case MONTableViewCellID_Rating :
return [rate objectForKey:#"average"];
case MONTableViewCellID_TotalRating :
return [rate objectForKey:#"totalRatings"];
default : {
assert(0 && "invalid row");
return #"";
}
}
}
- (NSString *)separatorForRow:(NSUInteger)row
{
switch (row) {
case MONTableViewCellID_Name :
return #" ";
case MONTableViewCellID_Address :
case MONTableViewCellID_Age :
case MONTableViewCellID_Occupation :
case MONTableViewCellID_Rating :
case MONTableViewCellID_TotalRating :
return #" : ";
default : {
assert(0 && "invalid row");
return #"";
}
}
}
- (NSString *)textLabelTextForRow:(NSUInteger)row
{
return [NSString stringWithFormat:#"%#%#%#", [self lhsTextForRow:row], [self separatorForRow:row], [self rhsTextForRow:row]];
}
- (void)updateTextLabel
{
cell.textLabel.text = [self textLabelTextForRow:indexPath.row];
cell.accessoryType = [self tableViewAccessoryTypeForRow:indexPath.row];
}
#end
Another overengineered option that you may be able to steal some nuggets from is the object based approach:
MONTableViewStuff.h
typedef enum MONTableViewCellID {
MONTableViewCellID_Name = 0,
MONTableViewCellID_Address,
MONTableViewCellID_Age,
MONTableViewCellID_Occupation,
MONTableViewCellID_Rating,
MONTableViewCellID_TotalRating
} MONTableViewCellID;
#interface MONTableViewStuff : NSObject
#property (nonatomic, copy, readonly) NSDictionary * dictionary;
#property (nonatomic, copy, readonly) NSDictionary * rate;
#end
MONTableViewStuff.m
#implementation MONTableViewStuff
#synthesize dictionary;
#synthesize rate;
- (id)init
{
self = [super init];
if (0 != self) {
/* create an array of presenters ordered by MONTableViewCellID */
presenters =
[NSArray arrayWithObjects:
[[NamePresenter new] autorelease],
[[AddressPresenter new] autorelease],
[[AgePresenter new] autorelease],
[[OccupationPresenter new] autorelease],
[[RatingPresenter new] autorelease],
[[TotalRatingPresenter new] autorelease],
nil
];
}
return self;
}
- (void)updateTableViewCell
{
NSObject<MONUITableViewCellPresenter>* presenter = [presenters objectAtIndex:indexPath.row];
[presenter updateUITableViewCell:cell tableViewStuff:self];
}
#end
Where the presenters' interface looked like so:
#protocol MONUITableViewCellPresenter < NSObject >
#required
- (void)updateUITableViewCell:(UITableViewCell *)cell tableViewStuff:(MONTableViewStuff *)tableViewStuff;
#end
// our base presenter which handles the cells
#interface DefaultPresenter : NSObject
/** #return UITableViewCellAccessoryNone */
- (UITableViewCellAccessoryType)cellAccessoryTypeForTableViewStuff:(MONTableViewStuff *)tableViewStuff;
- (void)updateUITableViewCell:(UITableViewCell *)cell tableViewStuff:(MONTableViewStuff *)tableViewStuff;
#end
// required overrides
#protocol DefaultPresenterSubclass <MONUITableViewCellPresenter>
#required
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff;
#end
// our specializations
#interface NamePresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
#interface AddressPresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
#interface AgePresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
#interface OccupationPresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
#interface RatingPresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
#interface TotalRatingPresenter : DefaultPresenter <DefaultPresenterSubclass>
#end
And their implementations looked like so:
#implementation DefaultPresenter
- (UITableViewCellAccessoryType)cellAccessoryTypeForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
#pragma unused (tableViewStuff)
return UITableViewCellAccessoryNone;
}
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
#pragma unused (tableViewStuff)
assert(0 && "specialization required");
return 0;
}
- (void)updateUITableViewCell:(UITableViewCell *)cell tableViewStuff:(MONTableViewStuff *)tableViewStuff
{
cell.accessoryType = [self cellAccessoryTypeForTableViewStuff:tableViewStuff];
cell.textLabel.text = [self cellTextForTableViewStuff:tableViewStuff];
}
#end
#implementation NamePresenter
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# %#",[tableViewStuff.dictionary valueForKey:#"firstname"], [tableViewStuff.dictionary valueForKey:#"lastname"]];
}
#end
#implementation AddressPresenter
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# : %#",#"Address",[tableViewStuff.dictionary valueForKey:#"address"]];
}
#end
#implementation AgePresenter
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# : %#",#"Age",[tableViewStuff.dictionary valueForKey:#"age"]];;
}
#end
#implementation OccupationPresenter
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# : %#",#"Occupation",[tableViewStuff.dictionary valueForKey:#"occupation"]];
}
#end
#implementation RatingPresenter
+ (UITableViewCellAccessoryType)cellAccessoryType
{
return UITableViewCellAccessoryDisclosureIndicator;
}
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# : %#",#"Rating",[tableViewStuff.rate valueForKey:#"average"]];
}
#end
#implementation TotalRatingPresenter
- (NSString *)cellTextForTableViewStuff:(MONTableViewStuff *)tableViewStuff
{
return [NSString stringWithFormat:#"%# : %#",#"Total Rating",[tableViewStuff.rate valueForKey:#"totalRatings"]];
}
#end
The thing you could do would be to make some kind of data objet containing the information you need to display in your stringWithFormat method.
And then make a NSDictionary that key value pair those object with the indexes...
But is all that work worth it in this particular case?
I doubt it.

Imlementation of Singleton Class

i have been using mostly the appDelegate class for global variables but recently i came to know that its not a gud way for keeping global variables so i am trying to make a singleton class as following
#implementation globalVar
static globalVar *_sharedInstance =nil;
#synthesize totalTime;
- (id) init
{
if (self = [super init])
{
}
return self;
}
+ (globalVar *) sharedInstance
{
#synchronized (self) {
if (_sharedInstance == nil) {
[[self alloc] init];
}
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (_sharedInstance == nil) {
_sharedInstance = [super allocWithZone:zone];
return _sharedInstance;
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
-(NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
// do nothing
}
- (id)autorelease
{
return self;
}
- (void) setTotalTime:(NSString *)time
{
#synchronized(self) {
if (totalTime != time) {
[totalTime release];
totalTime = [NSString stringWithFormat:#"%#",time];
}
}
//NSLog(#"time %#",totalTime);
}
-(NSString *)getTotalTime
{
#synchronized(self) {
//NSLog(#"total %#",totalTime);
return totalTime;
}
}
when i set the value for totaltime in my appDelegate class and retrieve it in that class only i get the correct value. but when i only retrieve the value in some other class i get BAD EXCESS. i first create the sharedinstance and then only call this method then why am i getting this error??
globalVar *myEngine = [globalVar sharedInstance];
NSLog(#"about %#",[myEngine totalTime]);
in my app delegate
globalVar *myEngine = [globalVar sharedInstance];
[myEngine setTotalTime:totalTime];
NSLog(#"in app delegate%#",[myEngine getTotalTime]);
You're releasing totalTime but not retaining the new value, which means that when you access it it's already been released, causing a bad access exception.
You can correct this by changing the line where you set the value to include a call to retain:
totalTime = [[NSString stringWithFormat:#"%#",time] retain];
Have a look at the discussion here:
Is it good practice to use AppDelegate for data manipulation and Handling?

How do I get TTTableViewDataSource to work with AddressBook

I would like to get a TTPickerTextField to search and get data from the build in AddressBook, and I understand I should make my own data source class that implements the TTTableViewDataSource protocol. But how do I implement it so that it connects correctly with the build in AddressBook? Im a newbie, so combining the Address Book Programming Guide for iOS and the API for TTTableViewDataSource is very confusing to me, so please help with some hints or even example(s).
Thank you
Here is an ABDataSource, that does exactly this. I'm using this in one of my apps. It will not work out of the box, because it depends on my 'DSMEmailAddress' class, but I hope it will point you in the right direction.
You may use this code under the terms of the zlib licence.
#interface ABDataSource : TTListDataSource {
ABAddressBookRef _addressBookRef;
NSMutableArray* _allItems;
NSMutableArray* _delegates;
}
+ (ABDataSource*)abDataSource:(BOOL)forSearch;
#end
#implementation ABDataSource
+ (ABDataSource*)abDataSource:(BOOL)forSearch {
ABDataSource* dataSource = [[[ABDataSource alloc] init] autorelease];
return dataSource;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
[_allItems release];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// UITableViewDataSource
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView {
return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// TTTableViewDataSource
- (NSString*)tableView:(UITableView*)tableView labelForObject:(id)object {
DSMEmailAdress* field = object;
return field.name;
}
- (Class)tableView:(UITableView*)tableView cellClassForObject:(id)object {
return [DSMEmailAddressTableCell class];
}
- (void)tableView:(UITableView*)tableView prepareCell:(UITableViewCell*)cell
forRowAtIndexPath:(NSIndexPath*)indexPath {
cell.accessoryType = UITableViewCellAccessoryNone;
((TTTableViewCell*)cell).object =[_items objectAtIndex:indexPath.row];
}
- (void)search:(NSString*)text {
if (nil == _allItems) {
_addressBookRef = ABAddressBookCreate ();
NSArray* allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(_addressBookRef);
_allItems = [[NSMutableArray alloc] initWithCapacity:[allPeople count]]; // capacity is only a rough guess, but better than nothing
for (id record in allPeople) {
CFTypeRef emailProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonEmailProperty);
NSArray *emails = (NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
CFRelease(emailProperty);
for (NSString *email in emails) {
NSString* compositeName = (NSString *)ABRecordCopyCompositeName((ABRecordRef)record);
DSMEmailAdress* field = [[[DSMEmailAdress alloc] initWithName:compositeName mail:email] autorelease];
[compositeName release];
[_allItems addObject:field];
}
[emails release];
}
CFRelease(_addressBookRef);
_addressBookRef = nil;
[allPeople release];
allPeople = nil;
}
[_items release];
if (text.length) {
_items = [[NSMutableArray alloc] init];
for (DSMEmailAdress* mail in _allItems) {
if ([mail hasPrefix:text]) {
[_items addObject:mail];
}
}
if ([_items count]==0){
[_items release];
_items = nil;
}
} else {
_items = nil;
}
[_delegates perform:#selector(modelDidFinishLoad:) withObject:self];
}
#pragma mark TTModel
- (NSMutableArray*)delegates {
if (!_delegates) {
_delegates = TTCreateNonRetainingArray();
}
return _delegates;
}
- (BOOL)isLoadingMore {
return NO;
}
- (BOOL)isOutdated {
return NO;
}
- (BOOL)isLoaded {
return !!_allItems;
}
- (BOOL)isLoading {
return NO;
}
- (BOOL)isEmpty {
return !_items.count;
}
- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
}
- (void)invalidate:(BOOL)erase {
}
- (void)cancel {
[_delegates perform:#selector(modelDidCancelLoad:) withObject:self];
}
#end

How to implement initWithObjects?

How can I create a class with the initializer initWithObjects?
Or does it just make more sense to inherit from NSArray and work around it that way?
initWithObjects: is implemented using a C variable argument list. Here's an example implementation:
- (void)setContentByAppendingStrings:(NSString *)firstArg, ...
{
NSMutableString *newContentString = [NSMutableString string];
va_list args;
va_start(args, firstArg);
for (NSString *arg = firstArg; arg != nil; arg = va_arg(args, NSString*))
{
[newContentString appendString:arg];
}
va_end(args);
[contents autorelease];
contents = [newContentString retain];
}
See this page for more info.
#interface foo : NSObject {
NSArray* objects;
}
-(id)initWithObjects:(NSArray*)array;
#end
#implementation foo
-(id)initWithObjects:(NSArray*)array{
if(self = [super init]){
objects = array;
}
return self;
}
#end