Search Results

Search found 560 results on 23 pages for 'nsdictionary'.

Page 8/23 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Incompatible Types in Initialization

    - by jack
    I have the following code in a subroutine that produces an incompatible types in initialization error on the varVal library in the subroutine evaluateExpression: NSDictionary *varVal; for (int i=0; i<varCount; i++) { [varVal setObject:[(i+1)*2 stringValue] forKey:[i stringValue]]; } double result =[[self brain] evaluateExpression:[[self brain] expression] usingVariableValues:varVal]; My subroutine declaration in the brain.h file is: +(double)evaluateExpression:(id)anExpression usingVariableValues:(NSDictionary *)variables; I'd appreciate any help.

    Read the article

  • expecte ')' before className

    - by Akbarbuneri
    Hi I have a class DataObject as Header ::: #import <Foundation/Foundation.h> @interface DataObject : NSObject { NSString *erorrMessage; BOOL hasError; NSDictionary *dataValues; } @property(nonatomic, retain)NSString *erorrMessage; @property(nonatomic)BOOL hasError; @property(nonatomic, retain)NSDictionary *dataValues; @end Class Implementation:::: #import "DataObject.h" @implementation DataObject @synthesize erorrMessage; @synthesize hasError; @synthesize dataValues; @end And I have another class as DataManager Header as :::: #import <Foundation/Foundation.h> @interface DataManager : NSObject - (DataObject *)getData :(NSString*)url; @end Implementation :::: #import "DataManager.h" #import "DataObject.h" #import "JSON.h" @implementation DataManager - (DataObject *)getData :(NSString*)url{ DataObject* dataObject = [[DataObject alloc]init]; NSString *urlString = [NSString stringWithFormat:url]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; //TODO: Here we have to check the internet connection before requesting. NSError * erorrOnRequesting; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&erorrOnRequesting]; NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if( erorrOnRequesting != nil) { dataObject.hasError = YES; dataObject.erorrMessage = @"Error on requsting to the web server"; return dataObject; } NSError *errorOnParsing; SBJSON *json = [[SBJSON new] autorelease]; NSDictionary *dataValues = [json objectWithString:responseString error:&errorOnParsing]; [responseString release]; if(errorOnParsing != nil) { //TODO: We have to send the website a feedback that there is some problem on the server end. dataObject.hasError = YES; dataObject.erorrMessage = @"Error on parsing, the server returned invalid data."; return dataObject; } dataObject.hasError = NO; dataObject.dataValues = dataValues; return dataObject; } @end Now when I build I got an error in the DataManager header where I #import Dataobject header, it says "error: expected')' before DataObject" I don;t understand what I miss. Thanks for the help..

    Read the article

  • Objective-C FontAwesome

    - by sdover102
    I'm Attempting to get FontAwesome up and running on an iOS app and could use a little assistance. I have the following code for iOS: UIBarButtonItem * viewDeckButton = [[UIBarButtonItem alloc] initWithTitle:@"\uf0c9" style:UIBarButtonItemStyleBordered target:self.viewDeckController action:@selector(toggleLeftView)]; NSDictionary * customTextAttrs = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"FontAwesome" size:14.0], UITextAttributeFont, nil]; [viewDeckButton setTitleTextAttributes:customTextAttrs forState:UIControlStateNormal]; @"\uf0c9" corresponds to the css class, icon-reorder. The font appears to be installed on my system (see http://cl.ly/image/2F1x1z2H0i2N). I'm getting the standard box character, as if the font is not loaded (see http://madmonkdev.com/badchar.png). Any help would be appreciated.

    Read the article

  • iOS TableView crash loading different data

    - by jollyr0ger
    Hi to all! I'm developing a simple iOS app where there is a table view with some categories (CategoryViewController). When clicking one of this category the view will be passed to a RecipesListController with another table view with recipes. This recipes are loaded from different plist based on the category clicked. The first time I click on a category, the recipes list is loaded and shown correctely. If i back to the category list and click any of the category (also the same again) the app crash. And I don't know how. The viewWillAppear is ececuted correctely but after crash. Can you help me? If you need the entire project I can zip it for you. Ok? Here is the code of the CategoryViewController.h #import <Foundation/Foundation.h> #import "RecipeRowViewController.h" @class RecipesListController; @interface CategoryViewController : UITableViewController { NSArray *recipeCategories; RecipesListController *childController; } @property (nonatomic, retain) NSArray *recipeCategories; @end The CategoryViewControoler.m #import "CategoryViewCotroller.h" #import "NavAppDelegate.h" #import "RecipesListController.h" @implementation CategoryViewController @synthesize recipeCategories; - (void)viewDidLoad { // Create the categories NSArray *array = [[NSArray alloc] initWithObjects:@"Antipasti", @"Focacce", @"Primi", @"Secondi", @"Contorni", @"Dolci", nil]; self.recipeCategories = array; [array release]; // Set background image UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sfondo_app.png"]]; [self.tableView setBackgroundView:bgImg]; [bgImg release]; [self.tableView reloadData]; [super viewDidLoad]; } - (void)viewDidUnload { self.recipeCategories = nil; // [childController release]; [super viewDidUnload]; } - (void)dealloc { [recipeCategories release]; // [childController release]; [super dealloc]; } #pragma mark - #pragma mark Table data source methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [recipeCategories count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellId = @"RecipesCategoriesCellId"; // Try to reuse a cell or create a new one UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId] autorelease]; } // Get the right value and assign to the cell NSUInteger row = [indexPath row]; NSString *rowString = [recipeCategories objectAtIndex:row]; cell.textLabel.text = rowString; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; [rowString release]; return cell; } #pragma mark - #pragma mark Table view delegate methods - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (childController == nil) { childController = [[RecipesListController alloc] initWithStyle:UITableViewStyleGrouped]; } childController.title = @"Ricette"; childController.category = [indexPath row]; [self.navigationController pushViewController:childController animated:YES]; } @end The RecipesListController.h #import <Foundation/Foundation.h> #import "RecipeRowViewController.h" #define kRecipeArrayLink 0 #define kRecipeArrayDifficulty 1 #define kRecipeArrayFoodType 2 #define kRecipeAntipasti 0 #define kRecipeFocacce 1 #define kRecipePrimi 2 #define kRecipeSecondi 3 #define kRecipeContorni 4 #define kRecipeDolci 5 @class DisclosureDetailController; @interface RecipesListController : UITableViewController { NSInteger category; NSDictionary *recipesArray; NSArray *recipesNames; NSArray *recipesLinks; DisclosureDetailController *childController; } @property (nonatomic) NSInteger category; @property (nonatomic, retain) NSDictionary *recipesArray; @property (nonatomic, retain) NSArray *recipesNames; @property (nonatomic, retain) NSArray *recipesLinks; @end The RecipesListcontroller.m #import "RecipesListController.h" #import "NavAppDelegate.h" #import "DisclosureDetailController.h" @implementation RecipesListController @synthesize category, recipesArray, recipesNames, recipesLinks; - (void)viewDidLoad { // Set background image UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sfondo_app.png"]]; [self.tableView setBackgroundView:bgImg]; [bgImg release]; [self.tableView reloadData]; [super viewDidLoad]; } - (void)viewWillAppear:(BOOL)animated { if (self.recipesArray != nil) { // Release the arrays [self.recipesArray release]; [self.recipesNames release]; } // Load the dictionary NSString *path = nil; // Load a different dictionary, based on the category if (self.category == kRecipeAntipasti) { path = [[NSBundle mainBundle] pathForResource:@"recipes_antipasti" ofType:@"plist"]; } else if (self.category == kRecipeFocacce) { path = [[NSBundle mainBundle] pathForResource:@"recipes_focacce" ofType:@"plist"]; } else if (self.category == kRecipePrimi) { path = [[NSBundle mainBundle] pathForResource:@"recipes_primi" ofType:@"plist"]; } else if (self.category == kRecipeSecondi) { path = [[NSBundle mainBundle] pathForResource:@"recipes_secondi" ofType:@"plist"]; } else if (self.category == kRecipeContorni) { path = [[NSBundle mainBundle] pathForResource:@"recipes_contorni" ofType:@"plist"]; } else if (self.category == kRecipeDolci) { path = [[NSBundle mainBundle] pathForResource:@"recipes_dolci" ofType:@"plist"]; } NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; self.recipesArray = dict; [dict release]; // Save recipes names NSArray *array = [[recipesArray allKeys] sortedArrayUsingSelector: @selector(compare:)]; self.recipesNames = array; [self.tableView reloadData]; [super viewWillAppear:animated]; } - (void)viewDidUnload { self.recipesArray = nil; self.recipesNames = nil; self.recipesLinks = nil; // [childController release]; [super viewDidUnload]; } - (void)dealloc { [recipesArray release]; [recipesNames release]; [recipesLinks release]; // [childController release]; [super dealloc]; } #pragma mark - #pragma mark Table data source methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [recipesNames count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *RecipesListCellId = @"RecipesListCellId"; // Try to reuse a cell or create a new one UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RecipesListCellId]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RecipesListCellId] autorelease]; } // Get the right value and assign to the cell NSUInteger row = [indexPath row]; NSString *rowString = [recipesNames objectAtIndex:row]; cell.textLabel.text = rowString; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; [rowString release]; return cell; } #pragma mark - #pragma mark Table view delegate methods - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (childController == nil) { childController = [[DisclosureDetailController alloc] initWithNibName:@"DisclosureDetail" bundle:nil]; } childController.title = @"Dettagli"; NSUInteger row = [indexPath row]; childController.recipeName = [recipesNames objectAtIndex:row]; NSArray *recipeRawArray = [recipesArray objectForKey:childController.recipeName]; childController.recipeLink = [recipeRawArray objectAtIndex:kRecipeArrayLink]; childController.recipeDifficulty = [recipeRawArray objectAtIndex:kRecipeArrayDifficulty]; [self.navigationController pushViewController:childController animated:YES]; } @end This is the crash log Program received signal: “EXC_BAD_ACCESS”. (gdb) bt #0 0x00f0da63 in objc_msgSend () #1 0x04b27ca0 in ?? () #2 0x00002665 in -[RecipesListController viewWillAppear:] (self=0x4b38a00, _cmd=0x6d81a2, animated=1 '\001') at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:67 #3 0x00370c9a in -[UINavigationController _startTransition:fromViewController:toViewController:] () #4 0x0036b606 in -[UINavigationController _startDeferredTransitionIfNeeded] () #5 0x0037283e in -[UINavigationController pushViewController:transition:forceImmediate:] () #6 0x04f49549 in -[UINavigationControllerAccessibility(SafeCategory) pushViewController:transition:forceImmediate:] () #7 0x0036b4a0 in -[UINavigationController pushViewController:animated:] () #8 0x00003919 in -[CategoryViewController tableView:didSelectRowAtIndexPath:] (self=0x4b27ca0, _cmd=0x6d19e3, tableView=0x500c200, indexPath=0x4b2d650) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/CategoryViewCotroller.m:104 #9 0x0032a794 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] () #10 0x00320d50 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] () #11 0x000337f6 in __NSFireDelayedPerform () #12 0x00d8cfe3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ () #13 0x00d8e594 in __CFRunLoopDoTimer () #14 0x00ceacc9 in __CFRunLoopRun () #15 0x00cea240 in CFRunLoopRunSpecific () #16 0x00cea161 in CFRunLoopRunInMode () #17 0x016e0268 in GSEventRunModal () #18 0x016e032d in GSEventRun () #19 0x002c342e in UIApplicationMain () #20 0x00001c08 in main (argc=1, argv=0xbfffef58) at /Users/claudiocanino/Documents/iOS/CottoMangiato/main.m:15 Another bt log: (gdb) bt #0 0x00cd76a1 in __CFBasicHashDeallocate () #1 0x00cc2bcb in _CFRelease () #2 0x00002dd6 in -[RecipesListController setRecipesArray:] (self=0x6834d50, _cmd=0x4293, _value=0x4e3bc70) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:16 #3 0x00002665 in -[RecipesListController viewWillAppear:] (self=0x6834d50, _cmd=0x6d81a2, animated=1 '\001') at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:67 #4 0x00370c9a in -[UINavigationController _startTransition:fromViewController:toViewController:] () #5 0x0036b606 in -[UINavigationController _startDeferredTransitionIfNeeded] () #6 0x0037283e in -[UINavigationController pushViewController:transition:forceImmediate:] () #7 0x091ac549 in -[UINavigationControllerAccessibility(SafeCategory) pushViewController:transition:forceImmediate:] () #8 0x0036b4a0 in -[UINavigationController pushViewController:animated:] () #9 0x00003919 in -[CategoryViewController tableView:didSelectRowAtIndexPath:] (self=0x4b12970, _cmd=0x6d19e3, tableView=0x5014400, indexPath=0x4b2bd00) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/CategoryViewCotroller.m:104 #10 0x0032a794 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] () #11 0x00320d50 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] () #12 0x000337f6 in __NSFireDelayedPerform () #13 0x00d8cfe3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ () #14 0x00d8e594 in __CFRunLoopDoTimer () #15 0x00ceacc9 in __CFRunLoopRun () #16 0x00cea240 in CFRunLoopRunSpecific () #17 0x00cea161 in CFRunLoopRunInMode () #18 0x016e0268 in GSEventRunModal () #19 0x016e032d in GSEventRun () #20 0x002c342e in UIApplicationMain () #21 0x00001c08 in main (argc=1, argv=0xbfffef58) at /Users/claudiocanino/Documents/iOS/CottoMangiato/main.m:15 Thanks

    Read the article

  • NSURLConnection request seems to disappear into thin air

    - by ibergmark
    Hi Everybody! I'm having trouble with a NSURLConnection request. My app calls a routine called sayHello to identify a user's device. This code works fine for all devices I've tested it on, but for some devices the request just seems to disappear into thin air with no errors or popups on the device. One specific device that fails is an iPod Touch 2G running OS 3.1.3. The app start's fine and doesn't crash, and none of my error popup messages are displayed. I just can't understand why my server never receives the request since the call to initWithRequest returns a pointer. Any help is much appreciated. Thanks. Here's the relevant header info: @interface Globals : NSObject { UserItem *userData; NSURLConnection *urlConnection; NSString *imageCacheLocation; NSOperationQueue *opQueue; } Here's the implementation of sayHello: - (void)sayHello:(BOOL)updateVisits; { NSString *updString; if (updateVisits) updString = @"Y"; else updString = @"N"; NSDictionary *dataDict = [[NSDictionary alloc] initWithObjectsAndKeys: [[UIDevice currentDevice] uniqueIdentifier], @"id", kProgVersion, @"pv", @"1", @"pr", userData.tagID, @"tg", updString, @"uv", nil]; NSString *urlString = [[NSString alloc] initWithString:kHelloURL]; urlConnection = [self localPOST:dataDict toUrl:urlString delegate:self]; [dataDict release]; [urlString release]; } - (NSURLConnection *)localPOST:(NSDictionary *)dictionary toUrl:(NSString *)urlString delegate:(id)delegate { NSString *myBounds = [[NSString alloc] initWithString:@"0xKmYbOuNdArY"]; NSMutableData *myPostData = [[NSMutableData alloc] initWithCapacity:10]; NSArray *formKeys = [dictionary allKeys]; for (int i = 0; i < [formKeys count]; i++) { [myPostData appendData:[[NSString stringWithFormat:@"--%@\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; [myPostData appendData:[[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"\n\n%@\n", [formKeys objectAtIndex:i], [dictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]]; } [myPostData appendData:[[NSString stringWithFormat:@"--%@--\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; NSURL *myURL = [[NSURL alloc] initWithString:urlString]; NSMutableURLRequest *myRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]; NSString *myContent = [[NSString alloc] initWithFormat: @"multipart/form-data; boundary=%@", myBounds]; [myRequest setValue:myContent forHTTPHeaderField:@"Content-Type"]; [myRequest setHTTPMethod:@"POST"]; [myRequest setHTTPBody:myPostData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:delegate]; if (!connection) { [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Connection failed", @"alert title - connection failed") message: NSLocalizedString( @"Could not open a connection.", @"alert message - connection failed")]; } [myBounds release]; [myPostData release]; [myURL release]; [myRequest release]; [myContent release]; return connection; } - (void)handleNetworkError:(NSError *)error { if (networkErrorAlert) return; networkErrorAlert = YES; [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Network error", @"alert title - network error") message: [NSString stringWithFormat: NSLocalizedString( @"This app needs a network connection to function properly.", @"alert message - network error")] otherButtons:nil delegate:self]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { [urlConnection release]; urlConnection = nil; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self handleNetworkError:error]; [urlConnection release]; urlConnection = nil; }

    Read the article

  • Why does Keychain Services return the wrong keychain content?

    - by Graham Lee
    I've been trying to use persistent keychain references in an iPhone application. I found that if I created two different keychain items, I would get a different persistent reference each time (they look like 'genp.......1', 'genp.......2', …). However, attempts to look up the items by persistent reference always returned the content of the first item. Why should this be? I confirmed that my keychain-saving code was definitely creating new items in each case (rather than updating existing items), and was not getting any errors. And as I say, Keychain Services is giving a different persistent reference for each item. I've managed to solve my immediate problem by searching for keychain items by attribute rather than persistent references, but it would be easier to use persistent references so I'd appreciate solving this problem. Here's my code: - (NSString *)keychainItemWithName: (NSString *)name { NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; NSData *persistentRef = [NSData dataWithContentsOfFile: path]; if (!persistentRef) { NSLog(@"no persistent reference for name: %@", name); return nil; } NSArray *refs = [NSArray arrayWithObject: persistentRef]; //get the data CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecMatchItemList, refs); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecReturnData, kCFBooleanTrue); CFDataRef item = NULL; OSStatus result = SecItemCopyMatching(params, (CFTypeRef *)&item); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d retrieving keychain reference for name: %@", result, name); return nil; } NSString *token = [[NSString alloc] initWithData: (NSData *)item encoding: NSUTF8StringEncoding]; CFRelease(item); return [token autorelease]; } - (void)setKeychainItem: (NSString *)newToken forName: (NSString *)name { NSData *tokenData = [newToken dataUsingEncoding: NSUTF8StringEncoding]; //firstly, find out whether the item already exists NSDictionary *searchAttributes = [NSDictionary dictionaryWithObjectsAndKeys: name, kSecAttrAccount, kCFBooleanTrue, kSecReturnAttributes, nil]; NSDictionary *foundAttrs = nil; OSStatus searchResult = SecItemCopyMatching((CFDictionaryRef)searchAttributes, (CFTypeRef *)&foundAttrs); if (noErr == searchResult) { NSMutableDictionary *toStore = [foundAttrs mutableCopy]; [toStore setObject: tokenData forKey: (id)kSecValueData]; OSStatus result = SecItemUpdate((CFDictionaryRef)foundAttrs, (CFDictionaryRef)toStore); if (result != errSecSuccess) { NSLog(@"error %d updating keychain", result); } [toStore release]; return; } //need to create the item. CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecAttrAccount, name); CFDictionaryAddValue(params, kSecReturnPersistentRef, kCFBooleanTrue); CFDictionaryAddValue(params, kSecValueData, tokenData); NSData *persistentRef = nil; OSStatus result = SecItemAdd(params, (CFTypeRef *)&persistentRef); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d from keychain services", result); return; } NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; [persistentRef writeToFile: path atomically: NO]; [persistentRef release]; }

    Read the article

  • Register NSService with Command Alt NSKeyEquivalent

    - by mahal tertin
    my Application provides a Global Service. I'd like to install the service with a command-alt-key combination. the thing i do now is not very error prone and really hard to debug as don't really see what's happening: inside Info.plist: <key>NSServices</key> <array> <dict> <key>NSSendTypes</key> <array> <string></string> </array> <key>NSReturnTypes</key> <array> <string></string> </array> <key>NSMenuItem</key> <dict> <key>default</key> <string>Go To Window in ${PRODUCT_NAME}</string> </dict> <key>NSMessage</key> <string>bringZFToForegroundZoomOut</string> <key>NSPortName</key> <string>com.raskinformac.${PRODUCT_NAME:identifier}</string> </dict> </array> and in the code: CFStringRef serviceStatusName = (CFStringRef)[NSString stringWithFormat:@"%@ - %@ - %@", appIdentifier, appName, methodNameForService]; CFStringRef serviceStatusRoot = CFSTR("NSServicesStatus"); CFPropertyListRef pbsAllServices = (CFPropertyListRef) CFMakeCollectable ( CFPreferencesCopyAppValue(serviceStatusRoot, CFSTR("pbs")) ); // the user did not configure any custom services BOOL otherServicesDefined = pbsAllServices != NULL; BOOL ourServiceDefined = NO; if ( otherServicesDefined ) { ourServiceDefined = NULL != CFDictionaryGetValue((CFDictionaryRef)pbsAllServices, serviceStatusName); } NSUpdateDynamicServices(); NSMutableDictionary *pbsAllServicesNew = nil; if (otherServicesDefined) { pbsAllServicesNew = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary*)pbsAllServices]; } else { pbsAllServicesNew = [NSMutableDictionary dictionaryWithCapacity:1]; } NSDictionary *serviceStatus = [NSDictionary dictionaryWithObjectsAndKeys: (id)kCFBooleanTrue, @"enabled_context_menu", (id)kCFBooleanTrue, @"enabled_services_menu", @"@~r", @"key_equivalent", nil]; [pbsAllServicesNew setObject:serviceStatus forKey:(NSString*)serviceStatusName]; CFPreferencesSetAppValue ( serviceStatusRoot, (CFPropertyListRef) pbsAllServicesNew, CFSTR("pbs")); Boolean result = CFPreferencesAppSynchronize(CFSTR("pbs")); if (result) { NSUpdateDynamicServices(); JLog(@"successfully installed our alt-command-R service"); } else { ALog(@"couldn't install our alt-command-R service"); } and to change the service: // once installed, its's a bit tricky to set new ones (works only in RELEASE somehow?) // quit finder // open "~/Library/Preferences/pbs.plist" and remove ch.ana.Zoom - Reveal Window in Zoom - bringZFToForegroundZoomOut inside NSServicesStatus and save // start app // /System/Library/CoreServices/pbs -dump_pboard (to see if it hat actually done what we wanted, might be empty) // /System/Library/CoreServices/pbs (to add the new services) // /System/Library/CoreServices/pbs -dump_pboard (see new linking) // and then /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder -NSDebugServices MY.APP.IDENTIFIER to restart finder so my question: is there a easier way to enable a Service with cmd-option-key? if yes, i'd gladly implement it in my software.

    Read the article

  • Parsing nested JSON objects with JSON Framework for Objective-C

    - by Sheehan Alam
    I have the following JSON object: { "response": { "status": 200 }, "messages": [ { "message": { "user": "value" "pass": "value", "url": "value" } ] } } I am using JSON-Framework (also tried JSON Touch) to parse through this and create a dictionary. I want to access the "message" block and pull out the "user", "pass" and "url" values. In Obj-C I have the following code: // Create new SBJSON parser object SBJSON *parser = [[SBJSON alloc] init]; // Prepare URL request to download statuses from Twitter NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; // Perform request and get JSON back as a NSData object NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // Get JSON as a NSString from NSData response NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //Print contents of json-string NSArray *statuses = [parser objectWithString:json_string error:nil]; NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]); NSLog(@"Array Count: %d", [statuses count]); NSDictionary *results = [json_string JSONValue]; NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"]; for (NSDictionary *tweet in tweets) { NSString *url = [tweet objectForKey:@"url"]; NSLog(@"url is: %@",url); } I can pull out "messages" and see all of the "message" blocks, but I am unable to parse deeper and pull out the "user", "pass", and "url".

    Read the article

  • NSData-AES Class Encryption/Decryption in Cocoa

    - by David Schiefer
    hi, I am attempting to encrypt/decrypt a plain text file in my text editor. encrypting seems to work fine, but the decrypting does not work, the text comes up encrypted. I am certain i've decrypted the text using the word i encrypted it with - could someone look through the snippet below and help me out? Thanks :) Encrypting: NSAlert *alert = [NSAlert alertWithMessageText:@"Encryption" defaultButton:@"Set" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"Please enter a password to encrypt your file with:"]; [alert setIcon:[NSImage imageNamed:@"License.png"]]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { [[NSUserDefaults standardUserDefaults] setObject:[input stringValue] forKey:@"password"]; NSData *data; [self setString:[textView textStorage]]; NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute]; [textView breakUndoCoalescing]; data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length]) documentAttributes:dict error:outError]; NSData*encrypt = [data AESEncryptWithPassphrase:[input stringValue]]; [encrypt writeToFile:[absoluteURL path] atomically:YES]; Decrypting: NSAlert *alert = [NSAlert alertWithMessageText:@"Decryption" defaultButton:@"Open" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"This file has been protected with a password.To view its contents,enter the password below:"]; [alert setIcon:[NSImage imageNamed:@"License.png"]]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { NSLog(@"Entered Password - attempting to decrypt."); NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentOption]; NSData*decrypted = [[NSData dataWithContentsOfFile:[self fileName]] AESDecryptWithPassphrase:[input stringValue]]; mString = [[NSAttributedString alloc] initWithData:decrypted options:dict documentAttributes:NULL error:outError];

    Read the article

  • Generate JSON object with transactionReceipt

    - by Carlos
    Hi, I've been the past days trying to test my first in-app purchse iphone application. Unfortunately I can't find the way to talk to iTunes server to verify the transactionReceipt. Because it's my first try with this technology I chose to verify the receipt directly from the iPhone instead using server support. But after trying to send the POST request with a JSON onbject created using the JSON api from google code, itunes always returns a strange response (instead the "status = 0" string I wait for). Here's the code that I use to verify the receipt: - (void)recordTransaction:(SKPaymentTransaction *)transaction { NSString *receiptStr = [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding]; NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"algo mas",@"receipt-data",nil]; NSString *jsonString = [jsonDictionary JSONRepresentation]; NSLog(@"string to send: %@",jsonString); NSLog(@"JSON Created"); urlData = [[NSMutableData data] retain]; //NSURL *sandboxStoreURL = [[NSURL alloc] initWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; NSLog(@"will create connection"); [[NSURLConnection alloc] initWithRequest:request delegate:self]; } maybe I'm forgetting something in the request's headers but I think that the problem is in the method I use to create the JSON object. HEre's how the JSON object looks like before I add it to the HTTPBody : string to send: {"receipt-data":"{\n\t\"signature\" = \"AUYMbhY ........... D0gIjEuMCI7Cn0=\";\n\t\"pod\" = \"100\";\n\t\"signing-status\" = \"0\";\n}"} The responses I've got: complete response { exception = "java.lang.IllegalArgumentException: Property list parsing failed while attempting to read unquoted string. No allowable characters were found. At line number: 1, column: 0."; status = 21002; } Thanks a lot for your guidance.

    Read the article

  • iphone twitter posting

    - by user313100
    I have some twitter code I modified from: http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/ His code used view alerts to login and post to twitter but I wanted to change mine to use windows. It is mostly working and I can login and post to Twitter. However, when I try to post a second time, the program crashes with a: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFString text]: unrecognized selector sent to instance 0xc2d560' I'm a bit of a coding newbie so any help would be appreciated. If I need to post more code, ask. #import "TwitterController.h" #import "xmacros.h" #define XAGENTS_TWITTER_CONFIG_FILE DOC_PATH(@"xagents_twitter_conifg_file.plist") static TwitterController* agent; @implementation TwitterController BOOL isLoggedIn; @synthesize parentsv, sharedLink; -(id)init { self = [super init]; maxCharLength = 140; parentsv = nil; isLogged = NO; isLoggedIn = NO; txtMessage = [[UITextView alloc] initWithFrame:CGRectMake(30, 225, 250, 60)]; UIImageView* bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fb_message_bg.png"]]; bg.frame = txtMessage.frame; lblCharLeft = [[UILabel alloc] initWithFrame:CGRectMake(15, 142, 250, 20)]; lblCharLeft.font = [UIFont systemFontOfSize:10.0f]; lblCharLeft.textAlignment = UITextAlignmentRight; lblCharLeft.textColor = [UIColor whiteColor]; lblCharLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; txtUsername = [[UITextField alloc]initWithFrame:CGRectMake(125, 190, 150, 30)]; txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(125, 225, 150, 30)]; txtPassword.secureTextEntry = YES; lblId = [[UILabel alloc]initWithFrame:CGRectMake(15, 190, 100, 30)]; lblPassword = [[UILabel alloc]initWithFrame:CGRectMake(15, 225, 100, 30)]; lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(80, 170, 190, 30)]; lblId.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblPassword.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblTitle.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.textColor = [UIColor whiteColor]; lblPassword.textColor = [UIColor whiteColor]; lblTitle.textColor = [UIColor whiteColor]; txtMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.text = @"Username:"; lblPassword.text =@"Password:"; lblTitle.text = @"Tweet This Message"; lblId.textAlignment = UITextAlignmentRight; lblPassword.textAlignment = UITextAlignmentRight; lblTitle.textAlignment = UITextAlignmentCenter; txtUsername.borderStyle = UITextBorderStyleRoundedRect; txtPassword.borderStyle = UITextBorderStyleRoundedRect; txtMessage.delegate = self; txtUsername.delegate = self; txtPassword.delegate = self; login = [[UIButton alloc] init]; login = [UIButton buttonWithType:UIButtonTypeRoundedRect]; login.frame = CGRectMake(165, 300, 100, 30); [login setTitle:@"Login" forState:UIControlStateNormal]; [login addTarget:self action:@selector(onLogin) forControlEvents:UIControlEventTouchUpInside]; cancel = [[UIButton alloc] init]; cancel = [UIButton buttonWithType:UIButtonTypeRoundedRect]; cancel.frame = CGRectMake(45, 300, 100, 30); [cancel setTitle:@"Back" forState:UIControlStateNormal]; [cancel addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; post = [[UIButton alloc] init]; post = [UIButton buttonWithType:UIButtonTypeRoundedRect]; post.frame = CGRectMake(165, 300, 100, 30); [post setTitle:@"Post" forState:UIControlStateNormal]; [post addTarget:self action:@selector(onPost) forControlEvents:UIControlEventTouchUpInside]; back = [[UIButton alloc] init]; back = [UIButton buttonWithType:UIButtonTypeRoundedRect]; back.frame = CGRectMake(45, 300, 100, 30); [back setTitle:@"Back" forState:UIControlStateNormal]; [back addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; loading1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading1.frame = CGRectMake(140, 375, 40, 40); loading1.hidesWhenStopped = YES; [loading1 stopAnimating]; loading2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading2.frame = CGRectMake(140, 375, 40, 40); loading2.hidesWhenStopped = YES; [loading2 stopAnimating]; twitterWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow addSubview:txtUsername]; [twitterWindow addSubview:txtPassword]; [twitterWindow addSubview:lblId]; [twitterWindow addSubview:lblPassword]; [twitterWindow addSubview:login]; [twitterWindow addSubview:cancel]; [twitterWindow addSubview:loading1]; UIImageView* logo = [[UIImageView alloc] initWithFrame:CGRectMake(35, 165, 48, 48)]; logo.image = [UIImage imageNamed:@"Twitter_logo.png"]; [twitterWindow addSubview:logo]; [logo release]; twitterWindow2 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow2 addSubview:lblTitle]; [twitterWindow2 addSubview:lblCharLeft]; [twitterWindow2 addSubview:bg]; [twitterWindow2 addSubview:txtMessage]; [twitterWindow2 addSubview:lblURL]; [twitterWindow2 addSubview:post]; [twitterWindow2 addSubview:back]; [twitterWindow2 addSubview:loading2]; [twitterWindow2 bringSubviewToFront:txtMessage]; UIImageView* logo1 = [[UIImageView alloc] initWithFrame:CGRectMake(35, 155, 42, 42)]; logo1.image = [UIImage imageNamed:@"twitter-logo-twit.png"]; [twitterWindow2 addSubview:logo1]; [logo1 release]; twitterWindow.hidden = YES; twitterWindow2.hidden = YES; return self; } -(void) onStart { [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait]; twitterWindow.hidden = NO; [twitterWindow makeKeyWindow]; [self refresh]; if(isLogged) { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [twitterWindow2 makeKeyWindow]; } } - (void)textFieldDidBeginEditing:(UITextField *)textField { [textField becomeFirstResponder]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ const char* str = [text UTF8String]; int s = str[0]; if(s!=0) if((range.location + range.length) > maxCharLength){ return NO; }else{ int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; // this fix was done by Jackie //http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/#comment-38026299 if([text isEqualToString:@"\n"]){ [textView resignFirstResponder]; return FALSE; }else{ return YES; } } int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; return YES; } -(void) onLogin { [loading1 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString = [NSString stringWithFormat:@""]; NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } -(void) onCancel { [[NSUserDefaults standardUserDefaults] setValue:@"NotActive" forKey:@"Twitter"]; twitterWindow.hidden = YES; [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight]; } -(void) onPost { [loading2 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString; if(sharedLink){ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@\n%@",txtMessage.text,sharedLink]]; }else{ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@",txtMessage.text]]; } NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // release the connection, and the data object [connection release]; if(isAuthFailed){ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Login Failed" message:@"Invalid ID/Password" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; }else{ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Failed to connect to Twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } isAuthFailed = NO; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { isAuthFailed = NO; [loading1 stopAnimating]; [loading2 stopAnimating]; if(isLogged) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; txtMessage = @""; [self refresh]; } else { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyTwitterLoggedIn" object:nil userInfo:nil]; } isLogged = YES; isLoggedIn = YES; } -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSDictionary* config = [NSDictionary dictionaryWithObjectsAndKeys:txtUsername.text,@"username",txtPassword.text,@"password",nil]; [config writeToFile:XAGENTS_TWITTER_CONFIG_FILE atomically:YES]; if ([challenge previousFailureCount] == 0) { NSURLCredential *newCredential; newCredential=[NSURLCredential credentialWithUser:txtUsername.text password:txtPassword.text persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { isAuthFailed = YES; [[challenge sender] cancelAuthenticationChallenge:challenge]; } } -(void) refresh { NSDictionary* config = [NSDictionary dictionaryWithContentsOfFile:XAGENTS_TWITTER_CONFIG_FILE]; if(config){ NSString* uname = [config valueForKey:@"username"]; if(uname){ txtUsername.text = uname; } NSString* pw = [config valueForKey:@"password"]; if(pw){ txtPassword.text = pw; } } } + (TwitterController*)defaultAgent{ if(!agent){ agent = [TwitterController new]; } return agent; } -(void)dealloc { [super dealloc]; [txtMessage release]; [txtUsername release]; [txtPassword release]; [lblId release]; [lblPassword release]; [lblURL release]; [twitterWindow2 release]; [twitterWindow release]; } @end

    Read the article

  • Cocoa NSStream works with SSL, with socks5, but not at the same time

    - by Evan D
    Upon connecting (to an FTP, at first without SSL) I run: NSArray *objects = [NSArray arrayWithObjects:@"proxy.ip", [NSNumber numberWithInt:1080], NSStreamSOCKSProxyVersion5, @"user", @"pass", nil]; NSArray *keys = [NSArray arrayWithObjects:NSStreamSOCKSProxyHostKey, NSStreamSOCKSProxyPortKey, NSStreamSOCKSProxyVersionKey, NSStreamSOCKSProxyUserKey, NSStreamSOCKSProxyPasswordKey, nil]; NSDictionary *proxyDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setProperty:proxyDictionary forKey:NSStreamSOCKSProxyConfigurationKey]; [iStream open]; same for iStream. This allows me to connect succesfully through a socks5 proxy. If I continue without setProperty:proxyDictionary... (socks5 disabled) I would tell the server to switch to SSL, and then successfully apply these settings to the in/output streams, thus giving me a SSL connection: NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; // to allow selfsigned certificates: [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFReadStreamSetProperty((CFReadStreamRef)iStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); [iStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey]; same for oStream. All of which works fine if I disable socks5. If I turn it on (line 7 in the first snippit) I lose contact when applying the SSL settings. If I had to guess, I'd think it's losing some properties when applying (ssl) "settings"? Please help :) Evan

    Read the article

  • iPhone: Memory leak when using NSOperationQueue...

    - by MacTouch
    Hi, I'm sitting here for at least half an hour to find a memory leak in my code. I just replaced an synchronous call to a (touch) method with an asynchronous one using NSOperationQueue. The Leak Inspector reports a memory leak after I did the change to the code. What's wrong with the version using NSOperationQueue? Version without a MemoryLeak -(NSData *)dataForKey:(NSString*)ressourceId_ { NSString *path = [self cachePathForKey:ressourceId_]; // returns an autoreleased NSString* NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString* NSData *data = [[self memoryCache] valueForKey:cacheKey]; if (!data) { data = [self loadData:path]; // returns an autoreleased NSData* if (data) { [[self memoryCache] setObject:data forKey:cacheKey]; } } [[self touch:path]; return data; } Version with a MemoryLeak (I do not see any) -(NSData *)dataForKey:(NSString*)ressourceId_ { NSString *path = [self cachePathForKey:ressourceId_]; // returns an autoreleased NSString* NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString* NSData *data = [[self memoryCache] valueForKey:cacheKey]; if (!data) { data = [self loadData:path]; // returns an autoreleased NSData* if (data) { [[self memoryCache] setObject:data forKey:cacheKey]; } } NSInvocationOperation *touchOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(touch:) object:path]; [[self operationQueue] addOperation:touchOp]; [touchOp release]; return data; } And of course, the touch method does nothing special too. Just change the date of the file. -(void)touch:(id)path_ { NSString *path = (NSString *)path_ NSFileManager *fm = [NSFileManager defaultManager]; if ([fm fileExistsAtPath:path]) { NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil]; [fm setAttributes: attributes ofItemAtPath:path error:nil]; } }

    Read the article

  • Using NSURLRequest to pass key-value pairs to PHP script with POST

    - by Ralf Mclaren
    Hi, I'm fairly new to objective-c, and am looking to pass a number of key-value pairs to a PHP script using POST. I'm using the following code but the data just doesn't seem to be getting posted through. I tried sending stuff through using NSData as well, but neither seem to be working. NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys: @"bob", @"sender", @"aaron", @"rcpt", @"hi there", @"message", nil]; NSURL *url = [NSURL URLWithString:@"http://myserver.com/script.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[NSData dataWithBytes:data length:[data count]]]; NSURLResponse *response; NSError *err; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; NSLog(@"responseData: %@", content); This is getting sent to this simple script to perform a db insert: <?php $sender = $_POST['sender']; $rcpt = $_POST['rcpt']; $message = $_POST['message']; //script variables include ("vars.php"); $con = mysql_connect($host, $user, $pass); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) VALUES ($sender, $rcpt, $message)"); echo "complete" ?> Any ideas?

    Read the article

  • iPhone: Fastest way to create a binary Plist with simple key/value strings

    - by randombits
    What's the best way to create a binary plist on the iPhone with simple string based key/value pairs? I need to create a plist with a list of recipe and ingredients. I then want to be able to read this into an NSDictionary so I can do something like NSString *ingredients = [recipes objectForKey:@"apple pie"]; I'm reading in an XML data file through an HTTP request and want to parse all of the key value pairs into the plist. The XML might look something like: <recipes> <recipe> <name>apple pie</name> <ingredients>apples and pie</ingredients> </recipe> <recipe> <name>cereal</name> <ingredients>milk and some other ingredients</ingredients> </recipe> </recipes> Ideally, I'll be able to write this to a plist at runtime, and then be able to read it and turn it into an NSDictionary later at runtime as well.

    Read the article

  • Problem using AVAudioRecorder.

    - by tek3
    Hi all, I am facing a strange problem with AVAudioRecorder. In my application i need to record audio and play it. I am creating my player as : if(recorder) { if(recorder.recording) [recorder stop]; [recorder release]; recorder = nil; } NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/%@.caf",songTitle]]; NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0],AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatAppleIMA4],AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax],AVEncoderAudioQualityKey,nil]; recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] settings: recordSettings error: nil]; recorder.delegate = self; if ([recorder prepareToRecord] == YES){ [recorder record]; I am releasing and creating player every time i press record button. But the problem is that ,AVAudiorecorder is taking some time before starting to record , and so if i press record button multiple times continuously ,my application freezes for some time. The same code works fine without any problem when headphones are connected to device...there is no delay in recording, and the app doesn't freeze even if i press record button multiple times. Any help in this regard will be highly appreciated. Thanx in advance.

    Read the article

  • Add objects in relationship not work using MagicalRecord saveWithBlock

    - by yong ho
    The code to perform a save block: [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { for (NSDictionary *stockDict in objects) { NSString *name = stockDict[@"name"]; Stock *stock = [Stock MR_createInContext:localContext]; stock.name = name; NSArray *categories = stockDict[@"categories"]; if ([categories count] > 0) { for (NSDictionary *categoryObject in categories) { NSString *categoryId = categoryObject[@"_id"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoryId == %@", categoryId]; NSArray *matches = [StockCategory MR_findAllWithPredicate:predicate inContext:localContext]; NSLog(@"%@", matches); if ([matches count] > 0) { StockCategory *cat = [matches objectAtIndex:0]; [stock addCategoriesObject:cat]; } } } } } completion:^(BOOL success, NSError *error) { }]; The Stock Model: @class StockCategory; @interface Stock : NSManagedObject @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) NSSet *categories; @end @interface Stock (CoreDataGeneratedAccessors) - (void)addCategoriesObject:(StockCategory *)value; - (void)removeCategoriesObject:(StockCategory *)value; - (void)addCategories:(NSSet *)values; - (void)removeCategories:(NSSet *)values; @end The json look like this: [ { "name": "iPad mini ", "categories": [ { "name": "iPad", "_id": "538c655fae9b3e1502fc5c9e", "__v": 0, "createdDate": "2014-06-02T11:51:59.433Z" } ], }, { "name": "iPad Air ", "categories": [ { "name": "iPad", "_id": "538c655fae9b3e1502fc5c9e", "__v": 0, "createdDate": "2014-06-02T11:51:59.433Z" } ], } ] Open the core data pro, You can see only stock with the name of "iPad air" has it's categories saved. I just can't figure out why. You can see in the saveWithBlock part, I first find in the context for the same _id as in json, and then add the category object in the relationship. It's working, but not all of them. Why is that?

    Read the article

  • Google Reader API with Objective-C - Problem getting token

    - by JustinXXVII
    I am able to successfully get the SID (SessionID) for my Google Reader account. In order to obtain the feed and do other operations inside Google Reader, you have to obtain an authorization token. I'm having trouble doing this. Can someone shed some light? //Create a cookie to append to the GET request NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"SID",@"NSHTTPCookieName",self.sessionID,@"NSHTTPCookieValue",@".google.com",@"NSHTTPCookieDomain",@"/",@"NSHTTPCookiePath",@"NSHTTPCookieExpires",@"160000000000",nil]; NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary]; //The URL to obtain the Token from NSURL *tokenURL = [NSURL URLWithString:@"http://www.google.com/reader/api/0/token"]; NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL]; //Not sure if this is right: add cookie to array, extract the headers from the cookie inside the array...? [tokenRequest setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSArray arrayWithObjects:authCookie,nil]]]; //This gives me an Error 403 Forbidden in the didReceiveResponse of the delegate [NSURLConnection connectionWithRequest:tokenRequest delegate:self]; I get a 403 Forbidden error as the response from Google. I'm probably not doing it right. I set the dictionary values according to the documentation for NSHTTPCookie.

    Read the article

  • In the iPad SplitView template, where's the code that specifies which views are to be used in the Sp

    - by Dr Dork
    In the iPad Programming Guide, it gives the following code example for specifying the two views (firstVC and secondVC) that will be used in the SplitView... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MyFirstViewController* firstVC = [[[MyFirstViewController alloc] initWithNibName:@"FirstNib" bundle:nil] autorelease]; MySecondViewController* secondVC = [[[MySecondViewController alloc] initWithNibName:@"SecondNib" bundle:nil] autorelease]; UISplitViewController* splitVC = [[UISplitViewController alloc] init]; splitVC.viewControllers = [NSArray arrayWithObjects:firstVC, secondVC, nil]; [window addSubview:splitVC.view]; [window makeKeyAndVisible]; return YES; } but when I actually create a new SplitView project in Xcode, I don't see any code that specifies which views should be added to the SplitView. Here's the code from the SplitView template... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after app launch rootViewController.managedObjectContext = self.managedObjectContext; // Add the split view controller's view to the window and display. [window addSubview:splitViewController.view]; [window makeKeyAndVisible]; return YES; } Thanks in advance for all your help! I'm going to continue researching this question right now.

    Read the article

  • Working with images (CGImage), exif data, and file icons

    - by Nick
    What I am trying to do (under 10.6).... I have an image (jpeg) that includes an icon in the image file (that is you see an icon based on the image in the file, as opposed to a generic jpeg icon in file open dialogs in a program). I wish to edit the exif metadata, save it back to the image in a new file. Ideally I would like to save this back to an exact copy of the file (i.e. preserving any custom embedded icons created etc.), however, in my hands the icon is lost. My code (some bits removed for ease of reading): // set up source ref I THINK THE PROBLEM IS HERE - NOT GRABBING THE INITIAL DATA CGImageSourceRef source = CGImageSourceCreateWithURL( (CFURLRef) URL,NULL); // snag metadata NSDictionary *metadata = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL); // make metadata mutable NSMutableDictionary *metadataAsMutable = [[metadata mutableCopy] autorelease]; // grab exif NSMutableDictionary *EXIFDictionary = [[[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy] autorelease]; << edit exif >> // add back edited exif [metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary]; // get source type CFStringRef UTI = CGImageSourceGetType(source); // set up write data NSMutableData *data = [NSMutableData data]; CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)data,UTI,1,NULL); //add the image plus modified metadata PROBLEM HERE? NOT ADDING THE ICON CGImageDestinationAddImageFromSource(destination,source,0, (CFDictionaryRef) metadataAsMutable); // write to data BOOL success = NO; success = CGImageDestinationFinalize(destination); // save data to disk [data writeToURL:saveURL atomically:YES]; //cleanup CFRelease(destination); CFRelease(source); I don't know if this is really a question of image handling, file handing, post-save processing (I could use sip), or me just being think (I suspect the last). Nick

    Read the article

  • iphone reload tableView

    - by Brodie4598
    In the following code, I have determined that everything works, up until [tableView reloadData] i have NSLOGs set up in the table view delegate methods and none of them are getting called. I have other methods doing the same reloadData and it works perfectly. The only difference tha I am awayre of is tha this is in a @catch block. maybe you smart guys can see something i'm doing wrong... @catch (NSException * e) {////chart is user genrated logoView.image = nil; NSInteger row = [picker selectedRowInComponent:0]; NSString *selectedAircraft = [aircraft objectAtIndex:row]; NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *checklistPath = [[NSString alloc]initWithFormat:@"%@/%@.checklist",docsPath,selectedAircraft]; NSString *dataString = [NSString stringWithContentsOfFile:checklistPath encoding: NSUTF8StringEncoding error:NULL]; if ([dataString hasPrefix:@"\n"]) { dataString = [dataString substringFromIndex:1]; } NSArray *tempArray = [dataString componentsSeparatedByString:@"\n"]; NSDictionary *temporaryDictionary = [NSDictionary dictionaryWithObject: tempArray forKey:@"User Generated Checklist"]; self.names = temporaryDictionary; NSArray *tempArray2 = [NSArray arrayWithObject:@"01User Generated Checklist"]; self.keys = tempArray2; aircraftLabel.text = selectedAircraft; checklistSelectPanel.hidden = YES; [tableView reloadData]; }

    Read the article

  • How to switch from Core Data automatic lightweight migration to manual?

    - by Jaanus
    My situation is similar to this question. I am using lightweight migration with the following code, fairly vanilla from Apple docs and other SO threads. It runs upon app startup when initializing the Core Data stack. NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; NSError *error = nil; NSString *storeType = nil; if (USE_SQLITE) { // app configuration storeType = NSSQLiteStoreType; } else { storeType = NSBinaryStoreType; } persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; // the following line sometimes crashes on app startup if (![persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nil URL:[self persistentStoreURL] options:options error:&error]) { // handle the error } For some users, especially with slower devices, I have crashes confirmed by logs at the indicated line. I understand that a fix is to switch this to manual mapping and migration. What is the recipe to do that? The long way for me would be to go through all Apple docs, but I don't recall there being good examples and tutorials specifically for schema migration.

    Read the article

  • xcode may not respond to warning

    - by Frames84
    Hi all, Can't seem to get rid of a warning. The warning is: 'UIImage' may not respond to '-scaleToSize' above the @implmentation MyViewController I have this @implementation: @implementation UIImage (scale) -(UIImage*)scaleToSize:(CGSize)size { UIGraphicsBeginImageContext(size); [self drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } @end Then I have MyViewController implementation @implementation TodayNewsTableViewController @synthesize dataList; ...... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MainNewsCellIdentifier = @"MainNewsCellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease]; } NSUInteger row = [indexPath row]; NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row]; NSString *title = [stream valueForKey:@"title"]; if( ! [title isKindOfClass:[NSString class]] ) { cell.textLabel.text = @""; } else { cell.textLabel.text = title; } cell.textLabel.numberOfLines = 2; cell.textLabel.font =[UIFont systemFontOfSize:10]; cell.detailTextLabel.numberOfLines = 1; cell.detailTextLabel.font= [UIFont systemFontOfSize:8]; cell.detailTextLabel.text = [stream valueForKey:@"created"]; NSString *i = [NSString stringWithFormat:@"http://www.mywebsite.co.uk/images/%@", [stream valueForKey:@"image"]]; NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]]; UIImage *newsImage = [[UIImage alloc] initWithData:imageURL] ; UIImage *scaledImage = [newsImage scaleToSize:CGSizeMake(50.0f, 50.0f)]; // warning is appearing here. cell.imageView.image = scaledImage; [imageURL release]; [newsImage release]; return cell; } Thanks for your time in advance. Frames

    Read the article

  • How to convert an NSString to an unsigned int in Cocoa?

    - by Dave Gallagher
    My application gets handed an NSString containing an unsigned int. NSString doesn't have an [myString unsignedIntegerValue]; method. I'd like to be able to take the value out of the string without mangling it, and then place it inside an NSNumber. I'm trying to do it like so: NSString *myUnsignedIntString = [self someMethodReturningAString]; NSInteger myInteger = [myUnsignedIntString integerValue]; NSNumber *myNSNumber = [NSNumber numberWithInteger:myInteger]; // ...put |myNumber| in an NSDictionary, time passes, pull it out later on... unsigned int myUnsignedInt = [myNSNumber unsignedIntValue]; Will the above potentially "cut off" the end of a large unsigned int since I had to convert it to NSInteger first? Or does it look OK to use? If it'll cut off the end of it, how about the following (a bit of a kludge I think)? NSString *myUnsignedIntString = [self someMethodReturningAString]; long long myLongLong = [myUnsignedIntString longLongValue]; NSNumber *myNSNumber = [NSNumber numberWithLongLong:myLongLong]; // ...put |myNumber| in an NSDictionary, time passes, pull it out later on... unsigned int myUnsignedInt = [myNSNumber unsignedIntValue]; Thanks for any help you can offer! :)

    Read the article

  • should variable be released or not? iphone-sdk

    - by psebos
    Hi, In the following piece of code (from a book) data is an NSDictionary *data; defined in the header (no property). In the viewDidLoad of the controller the following occurs: - (void)viewDidLoad { [super viewDidLoad]; NSArray *keys = [NSArray arrayWithObjects:@"home", @"work", nil]; NSArray *homeDVDs = [NSArray arrayWithObjects:@"Thomas the Builder", nil]; NSArray *workDVDs = [NSArray arrayWithObjects:@"Intro to Blender", nil]; NSArray *values = [NSArray arrayWithObjects:homeDVDs, workDVDs, nil]; data = [[NSDictionary alloc] initWithObjects:values forKeys:keys]; } Since I am really new to objective-c can someone explain to me why I do not have to retain the variables keys,homeDVDs,workDVDs and values prior exiting the function? I would expect prior the data allocation something like: [keys retain]; [homeDVDs retain]; [workDVDs retain]; [values retain]; or not? Does InitWithObjects copies (recursively) all objects into a new table? Assuming we did not have the last line (data allocation) should we release all the NSArrays prior exiting the function (or we could safely assumed that all NSArrays will be autoreleased since there is no alloc for each one?) Thanks!!!!

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >