Translate

Home > Xcode Iphone

Xcode Iphone

XML Parsing and Saving Using GDataXML

Tuesday, October 25, 2011 Category : 0

My XML Have Following pattern

<Party>
  <Player>
    <Name>Butch</Name>
    <Level>1</Level>
    <Class>Fighter</Class>
  </Player>
  <Player>
    <Name>Shadow</Name>
    <Level>2</Level>
    <Class>Rogue</Class>
  </Player>
  <Player>
    <Name>Crak</Name>
    <Level>3</Level>
    <Class>Wizard</Class>
  </Player>
</Party>

So i have root node Party and a Child Node Player
After parsing XML i will be used two class for store data in memory. here is the two class


//Party.h
#import <Foundation/Foundation.h>

@interface Party : NSObject {
    NSMutableArray *_players;
}

@property (nonatomic, retain) NSMutableArray *players;

@end


//
//  Party.m
//  XMLTest
//
//  Created by Ray Wenderlich on 3/17/10.
//  Copyright 2010 Ray Wenderlich. All rights reserved.
//

#import "Party.h"

@implementation Party
@synthesize players = _players;

- (id)init {

    if ((self = [super init])) {
        self.players = [[[NSMutableArray alloc] init] autorelease];
    }
    return self;
   
}

- (void) dealloc {
    self.players = nil;   
    [super dealloc];
}

@end


//
//  Player.h
//  XMLTest
//
//  Created by Ray Wenderlich on 3/17/10.
//  Copyright 2010 Ray Wenderlich. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef enum {
    RPGClassFighter,
    RPGClassRogue,
    RPGClassWizard
} RPGClass;
   
@interface Player : NSObject {
    NSString *_name;
    int _level;
    RPGClass _rpgClass;
}

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int level;
@property (nonatomic, assign) RPGClass rpgClass;

- (id)initWithName:(NSString *)name level:(int)level rpgClass:(RPGClass)rpgClass;

@end


#import "Player.h"

@implementation Player
@synthesize name = _name;
@synthesize level = _level;
@synthesize rpgClass = _rpgClass;

- (id)initWithName:(NSString *)name level:(int)level rpgClass:(RPGClass)rpgClass {

    if ((self = [super init])) {
        self.name = name;
        self.level = level;
        self.rpgClass = rpgClass;
    }   
    return self;
   
}

- (void) dealloc {
    self.name = nil;   
    [super dealloc];
}

@end

use following function in any class where you want to build your parse method

#import "Party.h"
#import "Player.h"
#import "GDataXMLNode.h"

+ (Party *)loadParty {

    NSString *filePath = [self dataFilePath:FALSE];
    NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
    if (doc == nil) { return nil; }
   
    Party *party = [[[Party alloc] init] autorelease];
    //NSArray *partyMembers = [doc.rootElement elementsForName:@"Player"];
    NSArray *partyMembers = [doc nodesForXPath:@"//Party/Player" error:nil];
    for (GDataXMLElement *partyMember in partyMembers) {
               
        // Let's fill these in!
        NSString *name;
        int level;
        RPGClass rpgClass;

        // Name
        NSArray *names = [partyMember elementsForName:@"Name"];
        if (names.count > 0) {
            GDataXMLElement *firstName = (GDataXMLElement *) [names objectAtIndex:0];
            name = firstName.stringValue;
        } else continue;
               
        // Level
        NSArray *levels = [partyMember elementsForName:@"Level"];
        if (levels.count > 0) {
            GDataXMLElement *firstLevel = (GDataXMLElement *) [levels objectAtIndex:0];
            level = firstLevel.stringValue.intValue;
        } else continue;
       
        // Class
        NSArray *classes = [partyMember elementsForName:@"Class"];
        if (classes.count > 0) {
            GDataXMLElement *firstClass = (GDataXMLElement *) [classes objectAtIndex:0];
            if ([firstClass.stringValue caseInsensitiveCompare:@"Fighter"] == NSOrderedSame) {
                rpgClass = RPGClassFighter;
            } else if ([firstClass.stringValue caseInsensitiveCompare:@"Rogue"] == NSOrderedSame) {
                rpgClass = RPGClassRogue;
            } else if ([firstClass.stringValue caseInsensitiveCompare:@"Wizard"] == NSOrderedSame) {
                rpgClass = RPGClassWizard;
            } else {
                continue;
            }           
        } else continue;
       
        Player *player = [[[Player alloc] initWithName:name level:level rpgClass:rpgClass] autorelease];
        [party.players addObject:player];
       
    }
           
    [doc release];
    [xmlData release];
    return party;
   
}

+ (void)saveParty:(Party *)party {

    GDataXMLElement * partyElement = [GDataXMLNode elementWithName:@"Party"];
   
    for(Player *player in party.players) {
    
        GDataXMLElement * playerElement = [GDataXMLNode elementWithName:@"Player"];
        GDataXMLElement * nameElement = [GDataXMLNode elementWithName:@"Name" stringValue:player.name];
        GDataXMLElement * levelElement = [GDataXMLNode elementWithName:@"Level" stringValue:[NSString stringWithFormat:@"%d", player.level]];
        NSString *classString;
        if (player.rpgClass == RPGClassFighter) {
            classString = @"Fighter";
        } else if (player.rpgClass == RPGClassRogue) {
            classString = @"Rogue";
        } else if (player.rpgClass == RPGClassWizard) {
            classString = @"Wizard";
        }       
        GDataXMLElement * classElement = [GDataXMLNode elementWithName:@"Class" stringValue:classString];
       
        [playerElement addChild:nameElement];
        [playerElement addChild:levelElement];
        [playerElement addChild:classElement];
        [partyElement addChild:playerElement];
    }
   
    GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:partyElement] autorelease];
    NSData *xmlData = document.XMLData;
   
    NSString *filePath = [self dataFilePath:TRUE];
    NSLog(@"Saving xml data to %@...", filePath);
    [xmlData writeToFile:filePath atomically:YES];
       
}

Download GDataXML class from here

Polymorphism

Monday, October 24, 2011 Category : 0

Polymorphism is the ability of an object of one class to appear and be used as an object 
of another class. This is usually done by creating methods and attributes that are similar to 
those of another class. 
// file: Animal.h
#import <Foundation/Foundation.h>
 
@interface Animal : NSObject
{
        NSString *name;
}
 
@property(copy) NSString *name;
 
-(id) initWithName: (NSString *) aName;
 
-(void) talk;
 
@end
 
// =============================
 
// file: Animal.m
#import "Animal.h"
 
@implementation Animal
 
@synthesize name;
 
-(id) initWithName:(NSString *)aName {
        self = [super init];
 
        if ( self ) 
                self.name = aName;
 
        return self;
}
 
-(id) init {
        return [self initWithName:@""];
}
 
-(void) talk {
        NSLog(@"%@: Animals cannot talk!", name);
}
 
-(void) dealloc {
        if ( name )
                [name release];
        [super dealloc];
}
 
@end
 
// =============================
 
// file: Cat.h
#import "Animal.h"
 
@interface Cat : Animal
 
-(void) talk;
 
@end
 
// =============================
 
// file: Cat.m
#import "Cat.h"
 
@implementation Cat
 
-(void) talk {
        NSLog(@"%@: Meow!", name);
}
 
@end
 
// =============================
 
// file: Dog.h
#import "Animal.h"
 
@interface Dog : Animal
 
-(void) talk;
 
@end
 
// =============================
 
// file: Dog.m
#import "Dog.h"
 
@implementation Dog
 
-(void) talk {
        NSLog(@"%@: Woof! Woof!", name);
}
 
@end
 
// =============================
 
// file: main.m
#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Cat.h"
#import "Dog.h"
 
int main (int argc, const char * argv[])
{
        // all instances are behind a superclass type (Animal)
        Animal *animal = [[Animal alloc] initWithName:@"Animal"];
        Animal *missy = [[Cat alloc] initWithName:@"Missy"];
        Animal *mr = [[Cat alloc] initWithName:@"Mr. Mistophelees"];
        Animal *lassie = [[Dog alloc] initWithName:@"Lassie"];
 
        // polymorphic behavior
        [animal talk];
        [missy talk];
        [mr talk];
        [lassie talk];
 
        // releasing memory
        [animal release];
        [missy release];
        [mr release];
        [lassie release];
 
    return 0;
}
 
// =============================
 
// --> Console output:
// Animal: Animals cannot talk!
// Missy: Meow!
// Mr. Mistophelees: Meow!
// Lassie: Woof! Woof!

Xcode SQLLITE INSERT and SELECT

Tuesday, April 19, 2011 Category : 4

1. Create SQL Light DataBase By Following command in your MAC Terminal

o firstly we want to create a sqlite database file. Open up the Terminal and get into your project directory. Now type:
 sqlite3 names.db
This will create the file ‘names.db’ at the path your at in the Terminal. Now to check the database contents and close, type:
1> .tables
2> .quit

 create table allusers(user_id DECIMAL,user_name varchar(50));



2. Create a new objective-c class file with named "dbController" 


 in header file add following code 
--------------------------------------
#define DATABASE_NAME @"TweetUser.db"
#define DATABASE_TITLE @"Tweet User"


@interface dbController : NSObject {
NSMutableArray *_scoresArray ;
NSMutableArray *UserArray;
}

- (NSString *) getWritableDBPath;
-(void)createEditableCopyOfDatabaseIfNeeded;
-(void)saveUserInDatabase:(NSString *)user_id:(NSString *)user_name;
-(void)loadUserFromDatabase;
-(NSMutableString *)LoadData;
- (NSMutableArray *)FindUserFromDatabase:(NSString *)user_id;
@end

3. in implementaion file add following code



#import "dbController.h"
#import <sqlite3.h>

@implementation dbController


- (NSString *) getWritableDBPath {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:DATABASE_NAME];

}


static int loadTimesCallback(void *context, int count, char **values, char **columns)
{
    NSMutableArray *times = (NSMutableArray *)context;
    for (int i=0; i < count; i++) {
        const char *nameCString = values[i];
        [times addObject:[NSString stringWithUTF8String:nameCString]];
    }
    return SQLITE_OK;
}

- (void)loadUserFromDatabase
{
    NSString *file = [self getWritableDBPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:file]; 
// If its not a local copy set it to the bundle copy
if(!success) {
//file = [[NSBundle mainBundle] pathForResource:DATABASE_TITLE ofType:@"db"];
[self createEditableCopyOfDatabaseIfNeeded];
}
_scoresArray = [[NSMutableArray alloc] init];
    sqlite3 *database = NULL;
    if (sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
        sqlite3_exec(database, "select * from allusers", loadTimesCallback, _scoresArray, NULL);
    }
    sqlite3_close(database);
}


- (NSMutableArray *)FindUserFromDatabase:(NSString *)user_id
{
    NSString *file = [self getWritableDBPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:file]; 
// If its not a local copy set it to the bundle copy
if(!success) {
//file = [[NSBundle mainBundle] pathForResource:DATABASE_TITLE ofType:@"db"];
[self createEditableCopyOfDatabaseIfNeeded];
}
//[UserArray removeObjectsInArray:UserArray];
UserArray = [[NSMutableArray alloc] init];
    sqlite3 *database = NULL;
    if (sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
NSString *SQLSTMNT =  [NSString stringWithFormat:@"select * from allusers where user_id =%@",user_id];
const char *sql = [SQLSTMNT UTF8String];
        sqlite3_exec(database, sql, loadTimesCallback, UserArray, NULL);

    }
    sqlite3_close(database);
[UserArray release];
return UserArray;
}

-(NSMutableString *)LoadData {
// Update text
NSMutableString *content = [[NSMutableString alloc] init];
for (int i = 0; i < [_scoresArray count]; i++) {
NSString *data = [_scoresArray objectAtIndex:i];
if(((i+2)%2)==0) {
[content appendString:[NSString stringWithFormat:@"ID: %@",data]];
} else if(((i+1)%2)==0) {
NSLog(@"%d",((i+2) %2));
[content appendString:[NSString stringWithFormat:@"Name: %@",data]];
[content appendString:@"\n"];
}
}
[content release];
return content;
}


-(void)saveUserInDatabase:(NSString *)user_id:(NSString *)user_name {
// Copy the database if needed
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
//NSString *temp = [NSString stringWithFormat:@"insert into allusers (user_id,user_name) VALUES (%@,%@)",user_id,user_name];
const char *sqlStatement = "insert into allusers (user_id,user_name) VALUES (?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)    {
sqlite3_bind_text( compiledStatement, 1,[user_id UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text( compiledStatement, 2,[user_name UTF8String], -1, SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( @"Save Error: %s", sqlite3_errmsg(database) );
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}

-(void)createEditableCopyOfDatabaseIfNeeded 
{
    // Testing for existence
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;
    // The writable database does not exist, so copy the default to
    // the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
  stringByAppendingPathComponent:DATABASE_NAME];
    success = [fileManager copyItemAtPath:defaultDBPath
  toPath:writableDBPath
error:&error];
    if(!success)
    {
        NSAssert1(0,@"Failed to create writable database file with Message : '%@'.",
  [error localizedDescription]);
    }
}


@end
================================

4. Now in your class which is load by a xib file use following code


-(IBAction)btnAdd:(id)sender {
if(textfield.text != @"" && textID.text != @"") {

NSMutableArray *dataArr = [userDB FindUserFromDatabase:textID.text];
if([dataArr count]==0) {
// Insert into the database
[userDB saveUserInDatabase:textID.text:textfield.text];
[userDB loadUserFromDatabase];
// Update the table view contents
textView.text =[userDB LoadData];
}
[textfield resignFirstResponder];
[textID resignFirstResponder];
}
}

- (void)viewDidLoad {
    [super viewDidLoad];
userDB = [[dbController alloc]init];
[userDB loadUserFromDatabase];
// Update the table view
textView.text = [userDB LoadData];
}

5. Run XOCDE 
6. Source File 

Powered by Blogger.