Showing posts with label Objective C. Show all posts
Showing posts with label Objective C. Show all posts

Monday, May 9, 2011

Objectice C: Change data of NSarray

NSMutableArray *tableContent = [[NSMutableArray alloc] initWithObjects:
                    [NSMutableArray arrayWithObjects:@"a",@"b",@"c",nil],
                    [NSMutableArray arrayWithObjects:@"d",@"e",@"f",nil],
                    [NSMutableArray arrayWithObjects:@"g",@"h",@"i",nil],
                     nil];

[[tableContent objectAtIndex:0] replaceObjectAtIndex:1 withObject:@"new object"];

Source:
http://stackoverflow.com/questions/2088679/objective-c-accessing-changing-array-elements-in-a-multidimensional-array-nsar

Wednesday, May 4, 2011

objective C: convert from int to string

 
int numberYouAreTryingToConvert = 5;
NSString* convertedNumber = [NSString stringWithFormat:@"%d"
                                      ,numberYouAreTryingToConvert];
 
Reference:
http://stackoverflow.com/questions/1104815/how-to-...-example-code

Tuesday, April 26, 2011

Objective c: NSString uppercase and lowercase

NSString to lowercase:

searchText = [searchText lowercaseString];

NSString to uppercase:

searchText = [searchText uppercaseString];






IPhone: Custom Table Cell

In order to make a custom table cell you have to handle the cell contentView:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
   
    // Set up the cell...
    pinFreeNumberItem *cellValue = [tableData objectAtIndex:indexPath.row];
   
    UIView *myContentView = cell.contentView;
    UILabel* topLeftLabel = [[UILabel alloc] initWithFrame: CGRectMake(2, -6, 350, 30)];
    topLeftLabel.text = @"hi1";
   
    [myContentView addSubview:topLeftLabel];
   
    UILabel* bottomRightLabel = [[UILabel alloc] initWithFrame: CGRectMake(170, 24, 350, 15)];
    bottomRightLabel.text =@"hi2";
   
    [myContentView addSubview:bottomRightLabel];
   
    UILabel* bottomLeftLabel = [[UILabel alloc] initWithFrame: CGRectMake(2, 24, 150, 15)];
    bottomLeftLabel.text = @"hi3";
   
    [myContentView addSubview:bottomLeftLabel];
   
    return cell;
}

Resources:
http://stackoverflow.com/questions/5337340/custom-uitablecell
http://iphone.zcentric.com/2008/08/05/custom-uitableviewcell/

Tuesday, April 19, 2011

request to send from iphone data and files to server using http post


-(NSMutableURLRequest *)requestWithURL:(NSURL *)url withBody:(NSMutableDictionary *)body  withUrlAndAttachedFile:(NSString *)fileAndUrl withFileName:(NSString *)fileName withFileFormat:(NSString *)fileFormat

{
    NSMutableURLRequest *request;
    NSString *requestBody;
       
    request = [[NSMutableURLRequest alloc] initWithURL:url
                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                       timeoutInterval:60];
   
    request= [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_0\"; filename=\"%@.%@\"\r\n", fileName, fileFormat] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *postData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileAndUrl]];
    [postbody appendData:[NSData dataWithData:postData]];
    [postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   
   
    // iterate body dict
    NSEnumerator *enumerator = [body keyEnumerator];
    id key;
    // extra parens to suppress warning about using = instead of ==
    while((key = [enumerator nextObject])){
        //NSLog(@"key=%@ value=%@", key, [body objectForKey:key]);
        [postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[body objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
   
   
    // close form
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
   
   
    return request;
}
references:
http://stackoverflow.com/questions/4458112/mac-os-nsurlconnection-in-iteration

"UIApplication" undeclared (first use in this function)

you have to add this import line:

#import <UIKit/UIKit.h>


Tuesday, April 12, 2011

Read and Write Text Files on IPhone OS

/Method writes a string to a text file
-(void) writeToTextFile{
      //get the documents directory:
      NSArray *paths = NSSearchPathForDirectoriesInDomains
           (NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];

      //make a file name to write the data to using the documents directory:
      NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                   documentsDirectory];
      //create content - four lines of text
      NSString *content = @"One\nTwo\nThree\nFour\nFive";
      //save content to the documents directory
      [content writeToFile:fileName 
                   atomically:NO 
                       encoding:NSStringEncodingConversionAllowLossy 
                          error:nil];

}
 
 
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
      //get the documents directory:
      NSArray *paths = NSSearchPathForDirectoriesInDomains
                      (NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];

      //make a file name to write the data to using the documents directory:
      NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                   documentsDirectory];
      NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
         NSLog(@"content: %@" , content)
      [content release];

} 
Source:  
http://howtomakeiphoneapps.com/2009/06/reading-and-writing-text-files-in-iphone-os-3-0/

Friday, April 8, 2011

warning: passing argument 1 of 'localizedStringForKey:value:table:' from incompatible pointer type

 NSString *paramVia    = NSLocalizedString("share_on_twitter_url_via", nil);

there was missing something, so add @ to "share_on_twitter_url_via" : @"share_on_twitter_url_via"

 NSString *paramVia    = NSLocalizedString(@"share_on_twitter_url_via", nil);

Wednesday, April 6, 2011

Simple Custom loading alert view

UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(140, 100)];

NSString* messageTitleToUser = @"Favorites list";
 UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:messageTitleToUser message:@"loading..." delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];

  [alertView addSubview:spinner];
  [spinner startAnimating];
  [alertView show];

....
...
...

//if you programmatically want to close the alert view
 [alertView dismissWithClickedButtonIndex:0 animated:YES];
// stop spinner
[spinner stopAnimating];


References:
http://stackoverflow.com/questions/593234/how-to-use-activity-indicator-view-on-iphone


Friday, April 1, 2011

Objective-c Getting Started ".objc_class_name_NSObject", referenced from

Following the http://www.otierney.net/objective-c.html#gettingstarted tutorial, I got the following error:

".objc_class_name_NSObject", referenced from:
.objc_class_name_Fraction in Fraction.o
"_objc_msgSend", referenced from:

It was caused because there was missing a link to a framework: "Foundation.framework".

So, you can add existing frameworks to you project in XCode4 following these steps:

  1. In the project navigator, select your project
  2. Double click your target
  3. Select the 'Build Phases' tab
  4. Open 'Link Binaries With Libraries' expander
  5. Click the '+' button
  6. Select your framework (Foundation.framework)
Done.

references:
http://forums.macnn.com/79/developer-center/391122/newby-trying-learn-obj-c-xcode/
http://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4

Real Objective C Hello World

Finally found a real HelloWorld in Objective c:

http://cupsofcocoa.wordpress.com/2010/09/03/objective-c-lesson-1-hello-world/

After that, we can know continue with this Complete Tutorial:

http://www.otierney.net/objective-c.html






Saturday, March 26, 2011

objectve c split string by end on line \n

NSString* answer;
......
...... (answer var is set and has a \n )
......

NSArray *firstSplit = [answer  componentsSeparatedByString:@"\r\n"];

Friday, March 25, 2011

printing addressBook multivalue identifier

ABMultiValueIdentifier identifier;

....
....
....


NSLog(@"identifier");
NSLog(@"%i" , identifier);

source: http://www.roseindia.net/tutorial/iphone/examples/nslog/nslogintegerexample.html

Assertion failed: (((ABCMultiValue *)multiValue)->flags.isMutable), function ABMultiValueAddValueAndLabel

I Had this code

ABMultiValueRef multiPhone = ABRecordCopyValue(person, kABPersonPhoneProperty);
// here y was getting the error: Assertion failed: (((ABCMultiValue *)multiValue)->flags.isMutable), //function ABMultiValueAddValueAndLabel
ABMultiValueAddValueAndLabel(multiPhone, @"1111111111", kABOtherLabel ,NULL);

It was because, in order to add some values to multiPhones var, this had to be mutable, it means to be ABMutableMultiValueRef type, so:

ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutableCopy(multiPhones);
ABMultiValueAddValueAndLabel(multiPhone, @"1111111111", kABOtherLabel ,NULL);

that's all.









Friday, March 18, 2011

Objective C: Logged User Singleton


//loggedUserDataSIngleton.h

#import <Foundation/Foundation.h>

@interface loggedUserDataSIngleton : NSObject {
    NSString *loginName;
}
   
@property (nonatomic, retain) NSString* loginName;
   
+(loggedUserDataSIngleton*)sharedMySingleton;
-(NSString*)obtainCurrentUserLoginName;

@end


//loggedUserDataSIngleton.m

#import "loggedUserDataSIngleton.h"


@implementation loggedUserDataSIngleton

@synthesize loginName;

static loggedUserDataSIngleton *_sharedMySingleton = nil;

+(loggedUserDataSIngleton*)sharedMySingleton
{
    @synchronized([loggedUserDataSIngleton class])
    {
        if (!_sharedMySingleton) {
            [[self alloc] init];
        }
       
        return _sharedMySingleton;
    }
   
    return nil;
}

+(id)alloc
{
    @synchronized([loggedUserDataSIngleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }
   
    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }
    return self;
}

-(NSString*)obtainCurrentUserLoginName {
    return self.loginName;
}

@end


then, in the .m you want to use the singleton, you have to import the loggedUserDataSIngleton.h:

#import "loggedUserDataSIngleton.h" 
....
....
....
....
// store login Name in singleton class  
//[loggedUserDataSIngleton sharedMySingleton].loginName = @"John";


// get stored login name
[[loggedUserDataSIngleton sharedMySingleton] loginName]




Reference:  http://getsetgames.com/2009/08/30/the-objective-c-singleton/

create person ABRecordRef: adding a contact to address book



CFErrorRef error = NULL;

ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();


ABRecordRef newPerson = ABPersonCreate();

ABRecordSetValue(newPerson, kABPersonFirstNameProperty, @"John", &error);

ABRecordSetValue(newPerson, kABPersonLastNameProperty, @"Doe", &error);

Here is the whole guide, it's very complete:


Source: http://www.modelmetrics.com/tomgersic/iphone-programming-adding-a-contact-to-the-iphone-address-book/

Wednesday, March 16, 2011

ASCII url encoding Objective C

 
NSString* escapedUrlString = [unescapedString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

Source: http://mesh.typepad.com/blog/2007/10/url-encoding-wi.html

Tuesday, March 15, 2011

getting value property from ABRecordRef - Extract Address Book Address Values Tutorial

I was searching for the way to get value properies from an ABRecordRef Object and I found out it was using ABRecordCopyValue:


NSString *name = (NSString *)ABRecordCopyValue(person
, kABPersonFirstNameProperty);
 
but the great thing I found was an Amazing Tutorial : 
Tutorial: Extract Address Book Address Values on iPhone OS