Search Results

Search found 2356 results on 95 pages for 'nsstring'.

Page 15/95 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Does a Category applied to NSString also apply to NSCFString via the "toll-free bridge"?

    - by half_brick
    We're integrating a library into an iPhone app which appears to use the google toolbox for iPhone internally. The google toolbox adds a method gtm_stringBySanitizingAndEscapingForXML to NSString. The problem is, whenever we attempt to make a call to this library we get [NSCFString gtm_stringBySanitizingAndEscapingForXML]: unrecognized selector sent to instance 0x272478 So it appears the library is calling that method on a NSCFString, to which the category does not apply. So... is it the case that the category will not apply across the toll-free bridge to CoreFoundation classes? If that's the case then we at least know why it's blowing up. Figuring out how to fix it is a different matter.

    Read the article

  • add different characters to a NSString one by one??

    - by hemant
    i am retrieving different characters from a string by using thsi function and adding 5 to them to display the corresponding character for eg. 'a' displays 'f' and 'h' displays 'm'.. but the problem is that i am not able to add these characters into a string which i can use to display to display like 'fm'...can anyone help?? heres the code strResult(mutablestring) is getting null only. `str=@"John"; int a=[str length]; for(i=0;i char ch=[str characterAtIndex:i]; ch=ch+5; temp=[NSString stringWithFormat:@"%c",ch]; [strResult appendString:temp]; NSLog(@"%c",ch); }`

    Read the article

  • How can I get the JSON array data from nsstring or byte in xcode 4.2?

    - by user1471568
    I'm trying to get values from nsdata class and doesn't work. here is my JSON data. { "count": 3, "item": [{ "id": "1", "latitude": "37.556811", "longitude": "126.922015", "imgUrl": "http://175.211.62.15/sample_res/1.jpg", "found": false }, { "id": "3", "latitude": "37.556203", "longitude": "126.922629", "imgUrl": "http://175.211.62.15/sample_res/3.jpg", "found": false }, { "id": "2", "latitude": "37.556985", "longitude": "126.92286", "imgUrl": "http://175.211.62.15/sample_res/2.jpg", "found": false }] } and here is my code -(NSDictionary *)getDataFromItemList { NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)]; NSDictionary *iTem = [[NSDictionary alloc]init]; iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil]; NSLog(@"id = %@",[iTem objectForKey:@"id"]); //for Test output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding]; NSLog(@"%@",output); return iTem; } how can I access every value in the JSON? Please help me.

    Read the article

  • becomeFirstResponder not working!!!

    - by vikinara
    In the below code becomeFirstResonder not working, only resignFirstresponder working...can anyone please help - (BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == txtDate) { [txtDate resignFirstResponder]; [txtTime becomeFirstResponder]; } if (textField == txtTime) { [txtTime resignFirstResponder]; [txtAddress becomeFirstResponder]; } if (textField == txtAddress) { [txtAddress resignFirstResponder]; [txtCity becomeFirstResponder]; } if (textField == txtCity) { [txtCity resignFirstResponder]; [txtState becomeFirstResponder]; } if(textField == txtState) { [txtState resignFirstResponder]; [txtZip becomeFirstResponder]; } if (textField == txtZip) { [txtZip resignFirstResponder]; } return NO; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { if(textField == txtDate) { NSString *dateString = txtDate.text; NSString *dateRegex = @"^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; NSPredicate *dateTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", dateRegex]; BOOL validateDate = [dateTest evaluateWithObject:dateString]; if(!validateDate){ UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Date Error." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtDate.text = nil; } } if(textField == txtTime) { NSString *timeString = txtTime.text; NSString *timeRegex = @"^(([0]?[0-5][0-9]|[0-9]):([0-5][0-9]))$"; NSPredicate *timeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", timeRegex]; BOOL validateTime = [timeTest evaluateWithObject:timeString]; if(!validateTime) { UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Incorrect Time Entry." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtTime.text = nil; } } if(textField == txtAddress) { NSString *addressString = txtAddress.text; NSString *addressRegex = @"^[a-z0-9 ]+$"; NSPredicate *addressTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", addressRegex]; BOOL validateAddress = [addressTest evaluateWithObject:addressString]; if(!validateAddress) { UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Incorrect State." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtAddress.text = nil; } } if(textField == txtState) { NSString *stateString = txtState.text; NSString *stateRegex = @"^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$"; NSPredicate *stateTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stateRegex]; BOOL validateState = [stateTest evaluateWithObject:stateString]; if(!validateState) { UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Incorrect State." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtState.text = nil; } } if(textField == txtCity) { NSString *cityString = txtCity.text; NSString *cityRegex = @"^[a-z ]+$"; NSPredicate *cityTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", cityRegex]; BOOL validateCity = [cityTest evaluateWithObject:cityString]; if(!validateCity) { UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Incorrect City." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtCity.text = nil; } } if(textField == txtZip) { NSString *zipString = txtZip.text; NSString *zipRegex = @"^[0-9]{5}([- /]?[0-9]{4})?$"; NSPredicate *zipTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", zipRegex]; BOOL validateZip = [zipTest evaluateWithObject:zipString]; if(!validateZip) { UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:nil message:@"Incorrect Zip." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert2 show]; [alert2 release]; txtZip.text = nil; } } return NO; }

    Read the article

  • Need help with memory leaks in RSS Reader

    - by Stilton
    I'm trying to write a simple RSS reader for the iPhone, and it appeared to be working fine, until I started working with Instruments, and discovered my App is leaking massive amounts of memory. I'm using the NSXMLParser class to parse an RSS feed. My memory leaks appear to be originating from the overridden delegate methods: - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string and - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName I'm also suspicious of the code that populates the cells from my parsed data, I've included the code from those methods and a few other key ones, any insights would be greatly appreciated. - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ([self.currentElement isEqualToString:@"title"]) { [self.currentTitle appendString:string]; } else if ([self.currentElement isEqualToString:@"link"]) { [self.currentURL appendString:string]; } else if ([self.currentElement isEqualToString:@"description"]) { [self.currentSummary appendString:string]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"item"]) { //asdf NSMutableDictionary *item = [[NSMutableDictionary alloc] init]; [item setObject:currentTitle forKey:@"title"]; [item setObject:currentURL forKey:@"URL"]; [item setObject:currentSummary forKey:@"summary"]; [self.currentTitle release]; [self.currentURL release]; [self.currentSummary release]; [self.stories addObject:item]; [item release]; } } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. // Set up the cell int index = [indexPath indexAtPosition: [indexPath length] - 1]; CGRect contentRect = CGRectMake(8.0, 4.0, 260, 20); UILabel *textLabel = [[UILabel alloc] initWithFrame:contentRect]; if (self.currentLevel == 0) { textLabel.text = [self.categories objectAtIndex: index]; } else { textLabel.text = [[self.stories objectAtIndex: index] objectForKey:@"title"]; } textLabel.textColor = [UIColor blackColor]; textLabel.font = [UIFont boldSystemFontOfSize:14]; [[cell contentView] addSubview: textLabel]; //[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]]; [textLabel autorelease]; return cell; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:@"item"]) { self.currentTitle = [[NSMutableString alloc] init]; self.currentURL = [[NSMutableString alloc] init]; self.currentSummary = [[NSMutableString alloc] init]; } if (currentElement != nil) { [self.currentElement release]; } self.currentElement = [elementName copy]; } - (void)dealloc { [currentElement release]; [currentTitle release]; [currentURL release]; [currentSummary release]; [currentDate release]; [stories release]; [rssParser release]; [storyTable release]; [super dealloc]; } // Override to support row selection in the table view. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here -- for example, create and push another view controller. // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil]; int index = [indexPath indexAtPosition: [indexPath length] - 1]; if (currentLevel == 1) { StoryViewController *storyViewController = [[StoryViewController alloc] initWithURL:[[stories objectAtIndex: index] objectForKey:@"URL"] nibName:@"StoryViewController" bundle:nil]; [self.navigationController pushViewController:storyViewController animated:YES]; [storyViewController release]; } else { RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil]; rvController.currentLevel = currentLevel + 1; rvController.rssIndex = index; [self.navigationController pushViewController:rvController animated:YES]; [rvController release]; } }

    Read the article

  • Model Object called in NSOutlineView DataSource Method Crashing App

    - by Alec Sloman
    I have a bewildering problem, hoping someone can assist: I have a model object, called Road. Here's the interface. @@@ @interface RoadModel : NSObject { NSString *_id; NSString *roadmapID; NSString *routeID; NSString *title; NSString *description; NSNumber *collapsed; NSNumber *isRoute; NSString *staff; NSNumber *start; NSArray *staffList; NSMutableArray *updates; NSMutableArray *uploads; NSMutableArray *subRoads; } @property (nonatomic, copy) NSString *_id; @property (nonatomic, copy) NSString *roadmapID; @property (nonatomic, copy) NSString *routeID; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *description; @property (nonatomic, copy) NSNumber *collapsed; @property (nonatomic, copy) NSNumber *isRoute; @property (nonatomic, copy) NSString *staff; @property (nonatomic, copy) NSNumber *start; @property (nonatomic, copy) NSArray *staffList; @property (nonatomic, copy) NSMutableArray *updates; @property (nonatomic, copy) NSMutableArray *uploads; @property (nonatomic, copy) NSMutableArray *subRoads; - (id)initWithJSONObject:(NSDictionary *)JSONObject; @end This part is fine. To give you some background, I'm translating a bunch of JSON into a proper model object so it's easier to work with. Now, I'm trying to display this in an NSOutlineView. This is where the problem is. In particular, I have created the table and a datasource. - (id)initWithRoads:(NSArray *)roads { if (self = [super init]) root = [[NSMutableArray alloc] initWithArray:roads]; return self; } - (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item { if (item == nil) return root.count; return 0; } - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item { return NO; } - (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item { if (item == nil) item = root; if (item == root) return [root objectAtIndex:index]; return nil; } - (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item { return [item title]; } In the final datasource method, it attempts to return the "title" string property of the model object, but for some reason crashes each time. I have checked that the method is taking in the correct object (I checked [item class] description], and it is the right object), but for some reason if I call any of the objects accessors the app immediately crashes. This is totally puzzling because in the init method, I can iterate through root (an array of RoadModel objects), and print any of its properties without issue. It is only when I'm trying to access the properties in any of the datasource methods that this occurs. I wonder if there is something memory-wise that is going on behind the scenes and I am not providing for it. If you can shed some light on to this situation, it would be greatly appreciated! Thanks in advance!

    Read the article

  • How to convert Unicode strings (\u00e2, etc) into NSString for display?

    - by karlbecker_com
    I am trying to support arbitrary unicode from a variety of international users. They have already put a bunch of data into sqlite databases on their iPhones, and now I want to capture the data into a database, then send it back to their device. Right now I am using a php page that is sending data back to from an internet mysql database. The data is saved in the mysql database properly, but when it's sent back it comes out as unicode text, such as Frank\u00e2\u0080\u0099s iPad instead of just Frank's iPad where the apostrophe should really be a curly apostrophe. The answer posted to another question indicates that there is no built-in Cocoa methods to convert the "\u00e2\u0080\u0099" portion of the unicode string from the webserver to an NSString object. Is this correct? That seems really surprising (and scarily disappointing), since Cocoa definitely allows input from many different Unicode characters, and I need to support any arbitrary language that I have never heard of, and all of the possible characters. I save them to and from the local sqlite database just fine now, but once I send it to a web server, then perhaps pull down different data, I want to ensure the data pulled from the web server is correctly formatted.

    Read the article

  • Solving the EXC_BAD_ACCESS in WhatATool Part 2

    - by Allen
    #import <Cocoa/Cocoa.h> @interface PolygonShape : NSObject { int numberOfSides, maximumNumberOfSides, minimumNumberOfSides; } @property (readwrite) int numberOfSides, maximumNumberOfSides, minimumNumberOfSides; @property (readonly) float angleInDegrees, angleInRadians; @property (readonly) NSString * name; @property (readonly) NSString * description; -(id) init; -(void) setNumberOfSides:(int)sides; -(void) setMinimumNumberOfSides:(int)min; -(void) setMaximumNumberOfSides:(int)max; -(float) angleInDegrees; -(float) angleInRadians; -(NSString *) name; -(id) initWithNumberOfSides:(int) sides minimumNumberOfSides:(int) min maximumNumberOfSides:(int) max; -(NSString *) description; -(void) dealloc; @end #import "PolygonShape.h" @implementation PolygonShape -(id) init { return [self initWithNumberOfSides:4 minimumNumberOfSides:3 maximumNumberOfSides:5]; } @synthesize numberOfSides, minimumNumberOfSides, maximumNumberOfSides, angleInRadians; -(void) setNumberOfSides:(int)sides { numberOfSides = sides; NSLog(@"The number of sides is off limit so the number of sides is %@.",sides); } -(void)setMaximumNumberOfSides:(int)max { if (maximumNumberOfSides <= 12) { maximumNumberOfSides = max; } } -(void)setMinimumNumberOfSides: (int)min { if (minimumNumberOfSides > 2) { minimumNumberOfSides = min; } } - (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max { if(self=[super init]) { [self setNumberOfSides:(int)sides]; [self setMaximumNumberOfSides:(int)max]; [self setMinimumNumberOfSides: (int)min]; } return self; } -(float) angleInDegrees { float anglesInDegrees = (180 * (numberOfSides - 2) / numberOfSides); return anglesInDegrees; } -(float)angleInRadiants { float anglesInRadiants = ((180 * (numberOfSides - 2) / numberOfSides) * (180 / M_PI)); return anglesInRadiants; } -(NSString *)name { NSString * output; switch (numberOfSides) { case 3: output = @"Triangle"; break; case 4: output = @"Square"; break; case 5: output = @"Pentagon"; break; case 6: output = @"Hexagon"; break; case 7: output = @"Heptagon"; break; case 8: output = @"Octagon"; break; case 9: output = @"Nonagon"; break; case 10: output = @"Decagon"; break; case 11: output = @"Hendecagon"; break; case 12: output = @"Dodecabgon"; break; default: output = @"Invalid number of sides: %i is greater than maximum of five allowed."; } return output; } -(NSString *)description { NSString * output; NSLog(@"Hello I am a %i-sided polygon (aka a %@) with angles of %f degrees (%f radians).", numberOfSides, output, [self angleInDegrees], [self angleInRadiants]); return [self description]; } -(void)dealloc { [super dealloc]; } @end #import <Foundation/Foundation.h> #import "PolygonShape.h" void PrintPathInfo() { NSLog(@"Section 1"); NSLog(@"--------------------"); NSString *path = [@"~" stringByExpandingTildeInPath]; NSLog(@"My home folder is at '%@'.", path); NSArray *pathComponent = [path pathComponents]; for (path in pathComponent) { NSLog(@"%@",path); } NSLog(@"--------------------"); NSLog(@"\n"); } void PrintProcessInfo() { NSLog(@"Section 2"); NSLog(@"--------------------"); NSString * processName = [[NSProcessInfo processInfo] processName]; int processIdentifier = [[NSProcessInfo processInfo] processIdentifier]; NSLog(@"Process Name: '%@', Process ID: '%i'", processName, processIdentifier); NSLog(@"--------------------"); NSLog(@"\n"); } void PrintBookmarkInfo() { NSLog(@"Section 3"); NSLog(@"--------------------"); NSArray * keys = [NSArray arrayWithObjects: @"Stanford University", @"Apple", @"CS193P", @"Stanford on iTunes U", @"Stanford Mall", nil]; NSArray * objects = [NSArray arrayWithObjects: [NSURL URLWithString: @"http://www.stanford.edu"], @"http://www.apple.com", @"http://cs193p.stanford.edu", @"http://itunes.stanford.edu", @"http://stanfordshop.com",nil]; NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys]; NSEnumerator * enumerator = [keys objectEnumerator]; for (id keys in dictionary) { NSLog(@"key: '%@', value: '%@'", keys, [dictionary objectForKey:keys]); } NSLog(@" "); NSLog(@"These are the ones that has the prefix 'Stanford'."); NSLog(@" "); id object; while (object = [enumerator nextObject]) { if ([object hasPrefix: @"Stanford"]) { NSLog(@"key: '%@', value: '%@'", object, [dictionary objectForKey:object]); } } NSLog(@"--------------------"); NSLog(@"\n"); } void PrintIntrospectionInfo() { NSLog(@"Section 4"); NSLog(@"--------------------"); SEL lowercase = @selector (lowercaseString); NSMutableArray * array = [NSMutableArray array]; [array addObject: [NSString stringWithString: @"Here is a string"]]; [array addObject: [NSDictionary dictionary]]; [array addObject: [NSURL URLWithString: @"http://www.stanford.edu"]]; [array addObject: [[NSProcessInfo processInfo]processName]]; for (id keys in array) { NSLog(@"\n"); NSLog(@"Class Name: %@", [keys className]); NSLog(@"Is Member of NSString: %@", [keys isMemberOfClass:[NSString class]]?@"Yes":@"No"); NSLog(@"Is Kind of NSString: %@", [keys isKindOfClass:[NSString class]]?@"Yes":@"No"); if ([keys respondsToSelector: lowercase]==YES) { NSLog(@"Responds to lowercaseString: %@",[keys respondsToSelector: lowercase]?@"Yes":@"No"); NSLog(@"lowercaseString is: %@", [keys performSelector: lowercase]); } else { NSLog(@"Responds to lowercaseString: %@",[keys respondsToSelector: lowercase]?@"Yes":@"No" ); } } NSLog(@"--------------------"); } void PrintPolygonInfo() { NSMutableArray * array = [NSMutableArray array]; PolygonShape * polygon1 = [[PolygonShape alloc]initWithNumberOfSides:4 minimumNumberOfSides:3 maximumNumberOfSides:7]; [array addObject:polygon1]; [array description]; PolygonShape * polygon2 = [[PolygonShape alloc]initWithNumberOfSides:6 minimumNumberOfSides:5 maximumNumberOfSides:9]; [array addObject:polygon2]; [array description]; PolygonShape * polygon3 = [[PolygonShape alloc]initWithNumberOfSides:12 minimumNumberOfSides:9 maximumNumberOfSides:12]; [array addObject:polygon3]; [array description]; [array release]; [polygon1 release]; [polygon2 release]; [polygon3 release]; } int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; PrintPathInfo(); PrintProcessInfo(); PrintBookmarkInfo(); PrintIntrospectionInfo(); PrintPolygonInfo(); [pool release]; return 0; } //The result was "EXC_BAD_ACCESS", but I couldn't figure out how to resolve this problem.

    Read the article

  • EKCalendar not added to iCal

    - by Alex75
    I have a strange behavior on my iPhone. I'm creating an application that uses calendar events (EventKit). The class that use is as follows: the .h one #import "GenericManager.h" #import <EventKit/EventKit.h> #define oneDay 60*60*24 #define oneHour 60*60 @protocol CalendarManagerDelegate; @interface CalendarManager : GenericManager /* * metodo che aggiunge un evento ad un calendario di nome Name nel giorno onDate. * L'evento da aggiungere viene recuperato tramite il dataSource che è quindi * OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; /* * metodo che aggiunge un evento per giorno compreso tra fromDate e toDate ad un * calendario di nome Name. L'evento da aggiungere viene recuperato tramite il dataSource * che è quindi OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; @end @protocol CalendarManagerDelegate <NSObject> // viene inviato quando il calendario necessita informazioni sull' evento da aggiungere - (void) calendarManagerDidCreateEvent:(EKEvent *) event; @end the .m one // // CalendarManager.m // AppCampeggioSingolo // // Created by CreatiWeb Srl on 12/17/12. // Copyright (c) 2012 CreatiWeb Srl. All rights reserved. // #import "CalendarManager.h" #import "Commons.h" #import <objc/message.h> @interface CalendarManager () @end @implementation CalendarManager + (void)requestToEventStore:(EKEventStore *)eventStore delegate:(id)delegate fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate name:(NSString *)name { if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { // ios >= 6.0 [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { [self addEventForCalendarWithName:name fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; } else { } }]; } else if (class_getClassMethod([EKCalendar class], @selector(calendarIdentifier)) != nil) { // ios >= 5.0 && ios < 6.0 [self addEventForCalendarWithName:name fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; } else { // ios < 5.0 EKCalendar *myCalendar = [eventStore defaultCalendarForNewEvents]; EKEvent *event = [self generateEventForCalendar:myCalendar fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; } } /* * metodo che recupera l'identificativo del calendario associato all'app o nil se non è mai stato creato. */ + (NSString *) identifierForCalendarName: (NSString *) name { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSDictionary *confCalendar = [NSDictionary dictionaryWithContentsOfFile:confFileName]; NSString *currentIdentifier = [confCalendar objectForKey:name]; return currentIdentifier; } /* * memorizza l'identifier del calendario */ + (void) saveCalendarIdentifier:(NSString *) identifier andName: (NSString *) name { if (identifier != nil) { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSMutableDictionary *confCalendar = [NSMutableDictionary dictionaryWithContentsOfFile:confFileName]; if (confCalendar == nil) { confCalendar = [NSMutableDictionary dictionaryWithCapacity:1]; } [confCalendar setObject:identifier forKey:name]; [confCalendar writeToFile:confFileName atomically:YES]; } } + (EKCalendar *)getCalendarWithName:(NSString *)name inEventStore:(EKEventStore *)eventStore withLocalSource: (EKSource *)localSource forceCreation:(BOOL) force { EKCalendar *myCalendar; NSString *identifier = [self identifierForCalendarName:name]; if (force || identifier == nil) { NSLog(@"create new calendar"); if (class_getClassMethod([EKCalendar class], @selector(calendarForEntityType:eventStore:)) != nil) { // da ios 6.0 in avanti myCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore]; } else { myCalendar = [EKCalendar calendarWithEventStore:eventStore]; } myCalendar.title = name; myCalendar.source = localSource; NSError *error = nil; BOOL result = [eventStore saveCalendar:myCalendar commit:YES error:&error]; if (result) { NSLog(@"Saved calendar %@ to event store. %@",myCalendar,eventStore); } else { NSLog(@"Error saving calendar: %@.", error); } [self saveCalendarIdentifier:myCalendar.calendarIdentifier andName:name]; } // You can also configure properties like the calendar color etc. The important part is to store the identifier for later use. On the other hand if you already have the identifier, you can just fetch the calendar: else { myCalendar = [eventStore calendarWithIdentifier:identifier]; NSLog(@"fetch an old-one = %@",myCalendar); } return myCalendar; } + (EKCalendar *)addEventForCalendarWithName: (NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *)eventStore withDelegate: (id<CalendarManagerDelegate>) delegate { // da ios 5.0 in avanti EKCalendar *myCalendar; EKSource *localSource = nil; for (EKSource *source in eventStore.sources) { if (source.sourceType == EKSourceTypeLocal) { localSource = source; break; } } @synchronized(self) { myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:NO]; if (myCalendar == nil) myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:YES]; NSLog(@"End synchronized block %@",myCalendar); } EKEvent *event = [self generateEventForCalendar:myCalendar fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; return myCalendar; } + (EKEvent *) generateEventForCalendar: (EKCalendar *) calendar fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *) eventStore withDelegate:(id<CalendarManagerDelegate>) delegate { EKEvent *event = [EKEvent eventWithEventStore:eventStore]; event.startDate=fromDate; event.endDate=toDate; [delegate calendarManagerDidCreateEvent:event]; [event setCalendar:calendar]; // ricerca dell'evento nel calendario, se ne trovo uno uguale non lo inserisco NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fromDate endDate:toDate calendars:[NSArray arrayWithObject:calendar]]; NSArray *matchEvents = [eventStore eventsMatchingPredicate:predicate]; if ([matchEvents count] > 0) { // ne ho trovati di gia' presenti, vediamo se uno e' quello che vogliamo inserire BOOL found = NO; for (EKEvent *fetchEvent in matchEvents) { if ([fetchEvent.title isEqualToString:event.title] && [fetchEvent.notes isEqualToString:event.notes]) { found = YES; break; } } if (found) { // esiste già e quindi non lo inserisco NSLog(@"OH NOOOOOO!!"); event = nil; } } return event; } #pragma mark - Public Methods + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { [self requestToEventStore:eventStore delegate:delegate fromDate:fromDate toDate: toDate name:name]; } else { retVal = NO; } return retVal; } + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; NSDate *dateCursor = fromDate; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { while (retVal && ([dateCursor compare:toDate] == NSOrderedAscending)) { NSDate *finish = [dateCursor dateByAddingTimeInterval:oneDay]; [self requestToEventStore:eventStore delegate:delegate fromDate: dateCursor toDate: finish name:name]; dateCursor = [dateCursor dateByAddingTimeInterval:oneDay]; } } else { retVal = NO; } return retVal; } @end In practice, on my iphone I get the log: fetch an old-one = (null) 19/12/2012 11:33:09.520 AppCampeggioSingolo [730:8 b1b] create new calendar 19/12/2012 11:33:09.558 AppCampeggioSingolo [730:8 b1b] Saved calendar EKCalendar every time I add an event, then I look and I can not find it on iCal calendar event he added. On the iPhone of a friend of mine, however, everything is working correctly. I doubt that the problem stems from the code, but just do not understand what it could be. I searched all day yesterday and part of today on google but have not found anything yet. Any help will be greatly appreciated EDIT: I forgot the call wich is [CalendarManager addEventForCalendarWithName: @"myCalendar" fromDate:fromDate toDate: toDate withDelegate:self]; in the delegate method simply set title and notes of the event like this - (void) calendarManagerDidCreateEvent:(EKEvent *) event { event.title = @"the title"; event.notes = @"some notes"; }

    Read the article

  • MKMap showing detail of annotations

    - by yeohchan
    I have encountered a problem of populating the description for each annotation. Each annotation works, but there is somehow an area when trying to click on it. Here is the code. the one in bold is the one that has the problem. -(void)viewDidLoad{ FlickrFetcher *fetcher=[FlickrFetcher sharedInstance]; NSArray *rec=[fetcher recentGeoTaggedPhotos]; for(NSDictionary *dic in rec){ NSLog(@"%@",dic); NSDictionary *string = [fetcher locationForPhotoID:[dic objectForKey:@"id"]]; double latitude = [[string objectForKey:@"latitude"] doubleValue]; double longitude = [[string objectForKey:@"longitude"]doubleValue]; if(latitude !=0 && latitude != 0 ){ CLLocationCoordinate2D coordinate1 = { latitude,longitude }; **NSDictionary *adress=[NSDictionary dictionaryWithObjectsAndKeys:[dic objectForKey:@"owner"],[dic objectForKey:@"title"],nil];** MKPlacemark *anArea=[[MKPlacemark alloc]initWithCoordinate:coordinate1 addressDictionary:adress]; [mapView addAnnotation:anArea]; } } } Here is what the Flickr class does: #import <Foundation/Foundation.h> #define TEST_HIGH_NETWORK_LATENCY 0 typedef enum { FlickrFetcherPhotoFormatSquare, FlickrFetcherPhotoFormatLarge } FlickrFetcherPhotoFormat; @interface FlickrFetcher : NSObject { NSManagedObjectModel *managedObjectModel; NSManagedObjectContext *managedObjectContext; NSPersistentStoreCoordinator *persistentStoreCoordinator; } // Returns the 'singleton' instance of this class + (id)sharedInstance; // // Local Database Access // // Checks to see if any database exists on disk - (BOOL)databaseExists; // Returns the NSManagedObjectContext for inserting and fetching objects into the store - (NSManagedObjectContext *)managedObjectContext; // Returns an array of objects already in the database for the given Entity Name and Predicate - (NSArray *)fetchManagedObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate; // Returns an NSFetchedResultsController for a given Entity Name and Predicate - (NSFetchedResultsController *)fetchedResultsControllerForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate; // // Flickr API access // NOTE: these are blocking methods that wrap the Flickr API and wait on the results of a network request // // Returns an array of Flickr photo information for photos with the given tag - (NSArray *)photosForUser:(NSString *)username; // Returns an array of the most recent geo-tagged photos - (NSArray *)recentGeoTaggedPhotos; // Returns a dictionary of user info for a given user ID. individual photos contain a user ID keyed as "owner" - (NSString *)usernameForUserID:(NSString *)userID; // Returns the photo for a given server, id and secret - (NSData *)dataForPhotoID:(NSString *)photoID fromFarm:(NSString *)farm onServer:(NSString *)server withSecret:(NSString *)secret inFormat:(FlickrFetcherPhotoFormat)format; // Returns a dictionary containing the latitue and longitude where the photo was taken (among other information) - (NSDictionary *)locationForPhotoID:(NSString *)photoID; @end

    Read the article

  • Public class: The best way to store and access NSMutableDictionary?

    - by meridimus
    I have a class to help me store persistent data across sessions. The problem is I want to store a running sample of the property list or "plist" file in an NSMutableArray throughout the instance of the Persistance class so I can read and edit the values and write them back when I need to. The problem is, as the methods are publicly defined I cannot seem to access the declared NSMutableDictionary without errors. The particular error I get on compilation is: warning: 'Persistence' may not respond to '+saveData' So it kind of renders my entire process unusable until I work out this problem. Here is my full persistence class (please note, it's unfinished so it's just to show this problem): Persistence.h #import <UIKit/UIKit.h> #define kSaveFilename @"saveData.plist" @interface Persistence : NSObject { NSMutableDictionary *saveData; } @property (nonatomic, retain) NSMutableDictionary *saveData; + (NSString *)dataFilePath; + (NSDictionary *)getSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level; + (void)writeSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level withData:(NSDictionary *)saveData; + (NSString *)makeCampaign:(NSUInteger)campaign andLevelKey:(NSUInteger)level; @end Persistence.m #import "Persistence.h" @implementation Persistence @synthesize saveData; + (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:kSaveFilename]; } + (NSDictionary *)getSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level { NSString *filePath = [self dataFilePath]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSLog(@"File found"); [[self saveData] setDictionary:[[NSDictionary alloc] initWithContentsOfFile:filePath]]; // This is where the warning "warning: 'Persistence' may not respond to '+saveData'" occurs NSString *campaignAndLevelKey = [self makeCampaign:campaign andLevelKey:level]; NSDictionary *campaignAndLevelData = [[self saveData] objectForKey:campaignAndLevelKey]; return campaignAndLevelData; } else { return nil; } } + (void)writeSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level withData:(NSDictionary *)saveData { NSString *campaignAndLevelKey = [self makeCampaign:campaign andLevelKey:level]; NSDictionary *saveDataWithKey = [[NSDictionary alloc] initWithObjectsAndKeys:saveData, campaignAndLevelKey, nil]; //[campaignAndLevelKey release]; [saveDataWithKey writeToFile:[self dataFilePath] atomically:YES]; } + (NSString *)makeCampaign:(NSUInteger)campaign andLevelKey:(NSUInteger)level { return [[NSString stringWithFormat:@"%d - ", campaign+1] stringByAppendingString:[NSString stringWithFormat:@"%d", level+1]]; } @end I call this class like any other, by including the header file in my desired location: @import "Persistence.h" Then I call the function itself like so: NSDictionary *tempSaveData = [[NSDictionary alloc] [Persistence getSaveWithCampaign:currentCampaign andLevel:currentLevel]];

    Read the article

  • "incomplete universal character name" with stringWithUTF8String

    - by Nasser
    hi, when i try to convert form utf-8 string to NSString like so: NSString *s = [NSString stringWithUTF8String:"\U0627\U0644\U0641\U0631\U0646"]; NSLog(@"%@", s); i get the compile error: incomplete universal character name note that it sometime just works fine: NSString *UAE = [NSString stringWithUTF8String:"\U0627\U0644\U0641\U0631\U0646"]; NSLog(@"%@", UAE); and the output: ???????? so why is that happening? please help.

    Read the article

  • GET request, iOS

    - by phnmnn
    I need to do this GET request: http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[] In browser I get response: { "Success":true, "Atava":[], "Pending":[], "CallWaiter":false } But in iOS it not work. i try: NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num]; NSURL *url = [NSURL URLWithString:requestedURL]; NSURLResponse *response; NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding]; NSLog(@"Reply: %@", theReply); OR NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num]; OR NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; [params setObject:@"Tax" forKey:@"Name"]; [params setObject:@"2.11" forKey:@"Price"]; [params setObject:@"1" forKey:@"Quantity"]; [params setObject:@"1" forKey:@"SerialID"]; [params setObject:@"" forKey:@"Remarks"]; [params setObject:@"" forKey:@"Toppings"]; NSData *jsonData = nil; NSString *jsonString = nil; if([NSJSONSerialization isValidJSONObject:params]) { jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil]; jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",jsonString); } NSString *get=[NSString stringWithFormat: @"&Items=%@", jsonString]; NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"GET"]; [request setTimeoutInterval:8]; [request setHTTPBody:getData]; [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; nothing doesn't work. How to fix it? Sorry for bad english.

    Read the article

  • Sending an image in a faceless email

    - by anurag
    I am trying to send a faceless email (sending an email without showing the interface), using the code below. I also want to attach an image to this email. Is this possible? - (void) sendEmailTo:(NSString *)toStr withSubject:(NSString *)subjectStr withBody:(NSString *)bodyStr { NSString *emailString=[[NSString alloc] initWithFormat:@"mailto:?to=%@&subject=%@&body=%@", [toStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [subjectStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [bodyStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailString]]; [emailString release]; }

    Read the article

  • sending image in a faceless email

    - by anurag
    I am trying to send a faceless(without showing the interface)email by using the code below: I also want to attach an image to this email can anybody suggest is it possible??? (void) sendEmailTo:(NSString *)toStr withSubject:(NSString *)subjectStr withBody:(NSString *)bodyStr { NSString *emailString=[[NSString alloc] initWithFormat:@"mailto:?to=%@&subject=%@&body=%@", [toStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [subjectStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], [bodyStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailString]]; [emailString release]; }

    Read the article

  • Memory Leaks - Objective-C

    - by reising1
    Can anyone help point out memory leaks? I'm getting a bunch within this method and I'm not sure exactly how to fix it. - (NSMutableArray *)getTop5AndOtherKeysAndValuesFromDictionary:(NSMutableDictionary *)dict { NSLog(@"get top 5"); int sumOfAllValues = 0; NSMutableArray *arr = [[[NSMutableArray alloc] init] retain]; for(NSString *key in dict){ NSString *value = [[dict objectForKey:key] retain]; [arr addObject:value]; sumOfAllValues += [value intValue]; } //sort values NSArray *sorted = [[arr sortedArrayUsingFunction:sort context:NULL] retain]; [arr release]; //top 5 values int sumOfTop5 = 0; NSMutableArray *top5 = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < 5; i++) { int proposedIndex = [sorted count] - 1 - i; if(proposedIndex >= 0) { [top5 addObject:[sorted objectAtIndex:([sorted count] - i - 1)]]; sumOfTop5 += [[sorted objectAtIndex:([sorted count] - i - 1)] intValue]; } } [sorted release]; //copy of all keys NSMutableArray *copyOfKeys = [[[NSMutableArray alloc] init] retain]; for(NSString *key in dict) { [copyOfKeys addObject:key]; } //copy of top 5 values NSMutableArray *copyOfTop5 = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < [top5 count]; i++) { [copyOfTop5 addObject:[top5 objectAtIndex:i]]; } //get keys with top 5 values NSMutableArray *outputKeys = [[[NSMutableArray alloc] init] retain]; for(int i = 0; i < [top5 count]; i++) { NSString *targetValue = [top5 objectAtIndex:i]; for(int j = 0; j < [copyOfKeys count]; j++) { NSString *key = [copyOfKeys objectAtIndex:j]; NSString *val = [dict objectForKey:key]; if([val isEqualToString:targetValue]) { [outputKeys addObject:key]; [copyOfKeys removeObjectAtIndex:j]; break; } } } [outputKeys addObject:@"Other"]; [top5 addObject:[[NSString stringWithFormat:@"%d",(sumOfAllValues - sumOfTop5)] retain]]; NSMutableArray *output = [[NSMutableArray alloc] init]; [output addObject:outputKeys]; [output addObject:top5]; NSMutableArray *percents = [[NSMutableArray alloc] init]; int sum = sumOfAllValues; float leftOverSum = sum * 1.0f; int count = [top5 count]; float val1, val2, val3, val4, val5; if(count >= 1) val1 = ([[top5 objectAtIndex:0] intValue] * 1.0f)/sum; else val1 = 0.0f; if(count >=2) val2 = ([[top5 objectAtIndex:1] intValue] * 1.0f)/sum; else val2 = 0.0f; if(count >= 3) val3 = ([[top5 objectAtIndex:2] intValue] * 1.0f)/sum; else val3 = 0.0f; if(count >= 4) val4 = ([[top5 objectAtIndex:3] intValue] * 1.0f)/sum; else val4 = 0.0f; if(count >=5) val5 = ([[top5 objectAtIndex:4] intValue] * 1.0f)/sum; else val5 = 0.0f; if(val1 >= .00001f) { NSMutableArray *a1 = [[NSMutableArray alloc] init]; [a1 addObject:[outputKeys objectAtIndex:0]]; [a1 addObject:[top5 objectAtIndex:0]]; [a1 addObject:[NSString stringWithFormat:@"%.01f",(val1*100)]]; [percents addObject:a1]; leftOverSum -= ([[top5 objectAtIndex:0] intValue] * 1.0f); } if(val2 >= .00001f) { NSMutableArray *a2 = [[NSMutableArray alloc] init]; [a2 addObject:[outputKeys objectAtIndex:1]]; [a2 addObject:[top5 objectAtIndex:1]]; [a2 addObject:[NSString stringWithFormat:@"%.01f",(val2*100)]]; [percents addObject:a2]; leftOverSum -= ([[top5 objectAtIndex:1] intValue] * 1.0f); } if(val3 >= .00001f) { NSMutableArray *a3 = [[NSMutableArray alloc] init]; [a3 addObject:[outputKeys objectAtIndex:2]]; [a3 addObject:[top5 objectAtIndex:2]]; [a3 addObject:[NSString stringWithFormat:@"%.01f",(val3*100)]]; [percents addObject:a3]; leftOverSum -= ([[top5 objectAtIndex:2] intValue] * 1.0f); } if(val4 >= .00001f) { NSMutableArray *a4 = [[NSMutableArray alloc] init]; [a4 addObject:[outputKeys objectAtIndex:3]]; [a4 addObject:[top5 objectAtIndex:3]]; [a4 addObject:[NSString stringWithFormat:@"%.01f",(val4*100)]]; [percents addObject:a4]; leftOverSum -= ([[top5 objectAtIndex:3] intValue] * 1.0f); } if(val5 >= .00001f) { NSMutableArray *a5 = [[NSMutableArray alloc] init]; [a5 addObject:[outputKeys objectAtIndex:4]]; [a5 addObject:[top5 objectAtIndex:4]]; [a5 addObject:[NSString stringWithFormat:@"%.01f",(val5*100)]]; [percents addObject:a5]; leftOverSum -= ([[top5 objectAtIndex:4] intValue] * 1.0f); } float valOther = (leftOverSum/sum); if(valOther >= .00001f) { NSMutableArray *a6 = [[NSMutableArray alloc] init]; [a6 addObject:[outputKeys objectAtIndex:5]]; [a6 addObject:[top5 objectAtIndex:5]]; [a6 addObject:[NSString stringWithFormat:@"%.01f",(valOther*100)]]; [percents addObject:a6]; } [output addObject:percents]; NSLog(@"mu - a"); //[arr release]; NSLog(@"mu - b"); //[copyOfKeys release]; NSLog(@"mu - c"); //[copyOfTop5 release]; NSLog(@"mu - c"); //[outputKeys release]; //[top5 release]; //[percents release]; return output; }

    Read the article

  • iPhone: Can access files in documents directory in Simulator, but not device

    - by Kevin Cupp
    Hi there! I'm writing an app that copies some contents of the bundle into the applications Document's directory, mainly images and media. I then access this media throughout the app from the Document's directory. This works totally fine in the Simulator, but not on the device. The assets just come up as null. I've done NSLog's and the paths to the files look correct, and I've confirmed that the files exist in the directory by dumping a file listing in the console. Any ideas? Thank you! EDIT Here's the code that copies to the Document's directory NSString *pathToPublicationDirectory = [NSString stringWithFormat:@"install/%d",[[[manifest objectAtIndex:i] valueForKey:@"publicationID"] intValue]]; NSString *manifestPath = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"xml" inDirectory:pathToPublicationDirectory]; [self parsePublicationAt:manifestPath]; // Get actual bundle path to publication folder NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:pathToPublicationDirectory]; // Then build the destination path NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", [[[manifest objectAtIndex:i] valueForKey:@"publicationID"] intValue]]]; NSError *error = nil; // If it already exists in the documents directory, delete it if ([fileManager fileExistsAtPath:destinationPath]) { [fileManager removeItemAtPath:destinationPath error:&error]; } // Copy publication folder to documents directory [fileManager copyItemAtPath:bundlePath toPath:destinationPath error:&error]; I am figuring out the path to the docs directory with this method: - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; } And here's an example of how I'm building a path to an image path = [NSString stringWithFormat:@"%@/%d/%@", [self applicationDocumentsDirectory], [[thisItem valueForKey:@"publicationID"] intValue], [thisItem valueForKey:@"coverImage"]];

    Read the article

  • Integrating twitpic OAuth for iPhone.

    - by asadqamber
    How can I integrate twitpic API with OAuth for posting an image from iPhone? Any help or tutorial? Currently I am doing... NSURL *twitpicURL = [NSURL URLWithString:@"http://api.twitpic.com/2/upload.format"]; theRequest = [NSMutableURLRequest requestWithURL:twitpicURL]; [theRequest setHTTPMethod:@"POST"]; // Set the params NSString *message = theMessage; [theRequest addValue:@"http://api.twitter.com/" forHTTPHeaderField:@"OAuth realm"]; [theRequest addValue:TWITPIC_API_KEY forHTTPHeaderField:@"oauth_consumer_key"]; [theRequest addValue:@"HMAC-SHA1" forHTTPHeaderField:@"oauth_signature_method"]; [theRequest addValue:USER_OAUTH_TOKEN forHTTPHeaderField:@"oauth_token"]; [theRequest addValue:USER_OAUTH_SECRET forHTTPHeaderField:@"oauth_secret"]; [theRequest addValue: @"1272325550" forHTTPHeaderField:@"oauth_timestamp"]; [theRequest addValue:nil forHTTPHeaderField:@"oauth_nonce"]; [theRequest addValue:@"1.0" forHTTPHeaderField:@"oauth_version"]; [theRequest addValue:nil forHTTPHeaderField:@"oauth_signature"]; NSMutableData *postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"source\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"lighttable"] dataUsingEncoding:NSUTF8StringEncoding]]; // Message [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n%@", message]dataUsingEncoding:NSUTF8StringEncoding]]; // Media [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media\"; filename=\"%@\"\r\n", @"doc_twitpic_image.jpg"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"Content-Type: image/jpg\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; // data as JPEG [postBody appendData:[[NSString stringWithFormat:@"Content-Transfer-Encoding: binary\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[NSData dataWithData:image]]; [theRequest setHTTPBody:postBody]; [theRequest setValue:[NSString stringWithFormat:@"%d", [postBody length]] forHTTPHeaderField:@"Content-Length"]; theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    Read the article

  • Why would delaying a thread response fix view corruption?

    - by Beth S
    6 times out of 10 my very simple iPhone app is getting a corrupted display on launch or crashes randomly. But it behaves fine in the simulator. The display corruption looks like mis-colored fonts, out of place font text, wrong background colors, etc. I've found a strange work-around.. when my thread delays by 2 seconds before calling the "done" notification, everything works swimmingly. The thread reads a web page and the "done" notification loads up a PickerView with strings. So what gives? Can I not safely initiate a threaded task from viewDidLoad? - (void) loadWebPage:(NSString *)urlAddition { NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init]; NSString *pageSource; NSError *err; NSString *urlString = [NSString stringWithString:@"http://server/%@", urlAddition]; pageSource = [NSString stringWithContentsOfURL:[NSURL URLWithString: urlString] encoding:NSUTF8StringEncoding error:&err]; [NSThread sleepForTimeInterval:2.0]; // THIS STOPS THE DISPLAY CORRUPTION [[NSNotificationCenter defaultCenter] postNotificationName:@"webDoneNotification" object:nil]; [subPool drain]; } - (void) webDoneNotification: (NSNotification *)pNotification { [mediaArray release]; mediaArray = [[NSArray arrayWithObjects: [NSString stringWithString:@"new pickerview text"], nil] retain]; [mediaPickerView reloadAllComponents]; [mediaPickerView selectRow:0 inComponent:0 animated:NO]; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { mediaArray = [[NSArray arrayWithObjects: [NSString stringWithString:@"init pickerview text"], nil] retain]; if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; myWebThread = [[WebThread alloc] initWithDelegate:self]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webDoneNotification:) name:@"webDoneNotification" object:nil]; [myWebThread performSelectorInBackground:@selector(loadWebPage:) withObject:@""]; } Thanks! Update: Even a delay of 0.1 seconds is enough to completely fix the problem.

    Read the article

  • retrieve my wall post in my native i phone application

    - by hardik
    hello all i want to retrieve my all the wall post that i have posted until now i am using this fql query from my native iphone application in order to fetch it but i think i am maiking some mistake please guide me how could i do that the following is my fql query to get wall post - (void)session:(FBSession*)session didLogin:(FBUID)uid { NSString *fql = [NSString stringWithFormat:@"SELECT comments, likes FROM stream WHERE post_id=100000182297319"]; NSLog(@"session key is %@",_session.sessionKey); NSLog(@"from global key is %@",[twitfacedemoAppDelegate getfacebookkey]); NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params]; this is my other delgate method to get the wall post but this code is not working - (void)request:(FBRequest*)request didLoad:(id)result { @try { NSLog(@"result is %@",result); if(result==nil) { UIAlertView *a=[[UIAlertView alloc]initWithTitle:@"Can't login" message:@"You cant login here." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil]; [a show]; [a release]; } else { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [[NSString alloc]initWithString:[user objectForKey:@"name"]]; NSLog(@"name is %@",name); _label.text = [NSString stringWithFormat:@"Logged in as %@", name]; NSString *globalfacebookname; globalfacebookname=[[NSString alloc]initWithString:name]; NSLog(@"value is %@",globalfacebookname); NSString *fid=[user objectForKey:@"uid"]; NSLog(@"FACEBOOK ID WITH STRING DATATYP %@",fid); [twitfacedemoAppDelegate fetchfacebookid:fid]; } } @catch (NSException * e) { NSLog(@"Problem in dialog didFailWithError:%@",e); } } please guide me how could i retrieve my all the post from facebook to my native iphone application through fql query thanks in advance

    Read the article

  • UITableView: NSMutableArray not appearing in table

    - by Michael Orcutt
    I'm new to objective c and iPhone programming. I can't seem to figure out why no cells will fill when I run this code. The xml content displays in the console log and xcode displays no errors. Can any help? - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if(![elementName compare:@"Goal"] ) { tempElement = [[xmlGoal alloc] init]; } else if(![elementName compare:@"Title"]) { currentAttribute = [NSMutableString string]; } else if(![elementName compare:@"Progress"]) { currentAttribute = [NSMutableString string]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if(![elementName compare:@"Goal"]) { [xmlElementObjects addObject:tempElement]; } else if(![elementName compare:@"Title"]) { NSLog(@"The Title of this event is %@", currentAttribute); [tempElement setTitled:currentAttribute]; } else if(![elementName compare:@"Progress"]) { NSLog(@"The Progress of this event is %@", currentAttribute); [tempElement setProgressed:currentAttribute]; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if(self.currentAttribute) { [self.currentAttribute appendString:string]; } } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [xmlElementObjects count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [mtableview dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... cell.textLabel.text = [xmlElementObjects objectAtIndex:indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { }

    Read the article

  • Basic problems (type inference or something else?) in Objective-C/Cocoa.

    - by Matt
    Hi, Apologies for how basic these questions are to some. Just started learning Cocoa, working through Hillegass' book, and am trying to write my first program (a GUI Cocoa app that counts the number of characters in a string). I tried this: NSString *string = [textField stringValue]; NSUInteger *stringLength = [string length]; NSString *countString = (@"There are %u characters",stringLength); [label setStringValue:countString]; But I'm getting errors like: Incompatible pointer conversion initializing 'NSUInteger' (aka 'unsigned long'), expected 'NSUInteger *'[-pedantic] for the first line, and this for the second line: Incompatible pointer types initializing 'NSUInteger *', expected 'NSString *' [-pedantic] I did try this first, but it didn't work either: [label setStringValue:[NSString stringWithFormat:@"There are %u characters",[[textField stringValue] length]]] On a similar note, I've only written in easy scripting languages before now, and I'm not sure when I should be allocing/initing objects and when I shouldn't. For example, when is it okay to do this: NSString *myString = @"foo"; or int *length = 5; instead of this: NSString *myString = [[NSString alloc] initWithString:"foo"]; And which ones should I be putting into the header files? I did check Apple's documentation, and CocoaDev, and the book I'm working for but without luck. Maybe I'm looking in the wrong places.. Thanks to anyone who takes the time to reply this: it's appreciated, and thanks for being patient with a beginner. We all start somewhere. EDIT Okay, I tried the following again: [label setStringValue:[NSString stringWithFormat:@"There are %u characters",[[textField stringValue] length]]] And it actually worked this time. Not sure why it didn't the first time, though I think I might have typed %d instead of %u by mistake. However I still don't understand why the code I posted at the top of my original post doesn't work, and I have no idea what the errors mean, and I'd very much like to know because it seems like I'm missing something important there.

    Read the article

  • xml parser not able to read all the nodes of the xml

    - by pankaj
    Hi i am trying to get values from all the nodes of a xml returned from a web service. But my code only reads first node, it does not read it further. code: -(void)parseData{ NuanceAppDelegate *appDel = (NuanceAppDelegate *)[[UIApplication sharedApplication] delegate]; NSString *url = @"http://cmweb.bpomatrix.net/SmartPhoneService.svc/login/"; url = [[[url stringByAppendingString:UserName] stringByAppendingString:@"/"] stringByAppendingString:Password]; url = [[url stringByAppendingString:@"/"] stringByAppendingString:appDel.CPAID]; NSLog(@"log: @%",url); NSURL *loginURL = [NSURL URLWithString:url]; NSXMLParser *home_Parser = [[NSXMLParser alloc] initWithContentsOfURL:loginURL]; [home_Parser setDelegate:self]; dict = [[NSMutableDictionary alloc] init]; [home_Parser parse]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{ if([elementName isEqualToString:@"Address"]) addressFound = TRUE; if([elementName isEqualToString:@"Name"]) nameFound = TRUE; if([elementName isEqualToString:@"LoyaltyNum"]) loyaltyNumFound = TRUE; if([elementName isEqualToString:@"City"]) cityFound = TRUE; if([elementName isEqualToString:@"Province"]) proFound = TRUE; if([elementName isEqualToString:@"Zip"]) zipFound = TRUE; //NSLog(@"Response %@",responseFound); } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ if(addressFound) { [dict setObject:string forKey:@"address"]; addressFound = FALSE; } else if(nameFound) { [dict setObject:string forKey:@"name"]; nameFound = FALSE; } else if(loyaltyNumFound) { [dict setObject:string forKey:@"loyaltyNum"]; loyaltyNumFound = FALSE; } else if(cityFound) { [dict setObject:string forKey:@"city"]; cityFound = FALSE; } else if(proFound) { [dict setObject:string forKey:@"province"]; proFound = FALSE; } else if(zipFound) { [dict setObject:string forKey:@"zip"]; zipFound = FALSE; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"clsUserProfile"]) { [self parsingOver]; } } -(void)parsingOver { NuanceAppDelegate *appDel = (NuanceAppDelegate *)[[UIApplication sharedApplication] delegate]; appDel.dictProfile = dict; }

    Read the article

  • I have a question about variable release in global class.

    - by Beomseok
    + (void)findAndCopyOfDatabaseIfNeeded{ NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [path objectAtIndex:0]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"DB"]; BOOL success = [fileManager fileExistsAtPath:databasePath]; if(!success){ NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB"]; [fileManager copyItemAtPath:resourcePath toPath:databasePath error:NULL]; } NSString *tracePath = [documentsDirectory stringByAppendingPathComponent:@"Trace"]; BOOL traceDir = [fileManager fileExistsAtPath:tracePath]; if(!traceDir){ NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Trace"]; [fileManager copyItemAtPath:resourcePath toPath:tracePath error:NULL]; } NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy"]; NSDate *today = [[NSDate alloc]init]; NSString *resultYear = [dateFormatter stringFromDate:today]; NSString *traceYearPath = [tracePath stringByAppendingPathComponent:resultYear]; BOOL yearDir = [fileManager fileExistsAtPath:tracePath]; if (!yearDir) { [fileManager createDirectoryAtPath:traceYearPath attributes:nil]; } //[resultYear release]; ? //[today release]; ? //[dateFormatter release]; ? } I'm using global class like this [ + (void)findAndCopyOfDatabaseIfNeeded ]. hm,, I don't know NSArray, NSString and NSFileManager are released. Variable release or Not release ? please advice for me.

    Read the article

  • Generating an NSDictionary from an SQL statement.

    - by Ed Wist
    I am trying to generate an NSDictonary that can be used to populate a listview with data I retrieved from an SQL statement. when I go to create an array and add them it adds the arrays for ALL my keys and not just for the current key. I've tried a removeAllObjects on the array but for some reason that destroys ALL my data that I already put in the dictionary. //open the database if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { const char *sql = "select alphaID, word from words order by word"; sqlite3_stmt *selectStatement; //prepare the select statement int returnValue = sqlite3_prepare_v2(database, sql, -1, &selectStatement, NULL); if(returnValue == SQLITE_OK) { NSMutableArray *NameArray = [[NSMutableArray alloc] init]; NSString *alphaTemp = [[NSString alloc] init]; //loop all the rows returned by the query. while(sqlite3_step(selectStatement) == SQLITE_ROW) { NSString *currentAlpha = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 1)]; NSString *definitionName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 2)]; if (alphaTemp == nil){ alphaTemp = currentAlpha; } if ([alphaTemp isEqualToString:(NSString *)currentAlpha]) { [NameArray addObject:definitionName]; } else if (alphaTemp != (NSString *)currentAlpha) { [self.words setObject:NameArray forKey:currentAlpha]; [NameArray removeAllObjects]; [NameArray addObject:definitionName]; } } } The Statement above adds all the "keys" but then removes all the array elements for all keys. if I take out the removeAllKeys it adds ALL the array elements for ALL keys. I don't want this I want it to add the array elements FOR the specific key then move on to the next key. in the end I want a NSDictonary with A (array) Alpha (string) Apple (string) B (array) Beta (string) Ball (string) C (array) Code (string) ...

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >