Search Results

Search found 190 results on 8 pages for 'nsmutabledictionary'.

Page 4/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • 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

  • Application shows low memory warning and crashes while loading images?

    - by Bhoomi
    I am using following code for loading images from server using following code.When i scroll UITableView application crashes. AsynchrohousImageView class .m file - (void)dealloc { [connection cancel]; //in case the URL is still downloading [connection release]; [data release]; [_imageView release]; [_activityIndicator release]; [super dealloc]; } - (void)loadImageFromURL:(NSURL*)url defaultImageName:(NSString *)defaultImageName showDefaultImage:(BOOL)defaultImageIsShown showActivityIndicator:(BOOL)activityIndicatorIsShown activityIndicatorRect:(CGRect)activityIndicatorRect activityIndicatorStyle:(UIActivityIndicatorViewStyle)activityIndicatorStyle { if (connection!=nil) { [connection release]; } if (data!=nil) { [data release]; } if ([[self subviews] count]>0) { [[[self subviews] objectAtIndex:0] removeFromSuperview]; // } if (defaultImageIsShown) { self.imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:defaultImageName]] autorelease]; } else { self.imageView = [[[UIImageView alloc] init] autorelease]; } [self addSubview:_imageView]; _imageView.frame = self.bounds; [_imageView setNeedsLayout]; [self setNeedsLayout]; if (activityIndicatorIsShown) { self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:activityIndicatorStyle] autorelease]; [self addSubview:_activityIndicator]; _activityIndicator.frame = activityIndicatorRect; _activityIndicator.center = CGPointMake(_imageView.frame.size.width/2, _imageView.frame.size.height/2); [_activityIndicator setHidesWhenStopped:YES]; [_activityIndicator startAnimating]; } NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData { if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; } [data appendData:incrementalData]; } - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection { [connection release]; connection=nil; _imageView.image = [UIImage imageWithData:data]; if (_activityIndicator) { [_activityIndicator stopAnimating]; } [data release]; data=nil; } - (UIImage*) image { UIImageView* iv = [[self subviews] objectAtIndex:0]; return [iv image]; } In ViewController Class Which loads image - (UITableViewCell *)tableView:(UITableView *)tV cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *reuseIdentifier =@"CellIdentifier"; ListCell *cell = (ListCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if (cell==nil) { cell = [[ListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]; NSMutableDictionary *dicResult = [arrResults objectAtIndex:indexPath.row]; NSURL *url=[NSURL URLWithString:[dicResult objectForKey:@"Image"]]; AsynchronousImageView *asyncImageView = [[AsynchronousImageView alloc] initWithFrame:CGRectMake(5, 10,80,80)]; [asyncImageView loadImageFromURL:url defaultImageName:@"DefaultImage.png" showDefaultImage:NO showActivityIndicator:YES activityIndicatorRect:CGRectMake(5, 10,30,30) activityIndicatorStyle:UIActivityIndicatorViewStyleGray]; // load our image with URL asynchronously [cell.contentView addSubview:asyncImageView]; // cell.imgLocationView.image = [UIImage imageNamed:[dicResult valueForKey:@"Image"]]; [asyncImageView release]; } if([arrResults count]==1) { UITableViewCell *cell1=[tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if(cell1==nil) cell1=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease]; NSMutableDictionary *dicResult = [arrResults objectAtIndex:0]; cell1.textLabel.text=[dicResult valueForKey:@"NoResults"]; return cell1; } else { NSMutableDictionary *dicResult = [arrResults objectAtIndex:indexPath.row]; NSString *title = [NSString stringWithFormat:@"%@ Bedrooms-%@", [dicResult valueForKey:KEY_NUMBER_OF_BEDROOMS],[dicResult valueForKey:KEY_PROPERTY_TYPE]]; NSString *strAddress = [dicResult valueForKey:KEY_DISPLAY_NAME]; NSString *address = [strAddress stringByReplacingOccurrencesOfString:@", " withString:@"\n"]; NSString *price = [dicResult valueForKey:KEY_PRICE]; NSString *distance = [dicResult valueForKey:KEY_DISTANCE]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.lblTitle.text = title; cell.lblAddress.text = address; if ([price length]>0) { cell.lblPrice.text = [NSString stringWithFormat:@"£%@",price]; }else{ cell.lblPrice.text = @""; } if ([distance length]>0) { cell.lblmiles.text = [NSString stringWithFormat:@"%.2f miles",[distance floatValue]]; }else{ cell.lblmiles.text = @""; } } return cell; } How can i resolve this? I have attached heapshot analysis screen shot of it.Here non Object consumes so much of memory what is that?

    Read the article

  • MPNowPlayingInfoCenter defaultCenter will not update or retrieve information

    - by Jayson Lane
    I'm working to update the MPNowPlayingInfoCenter and having a bit of trouble. I've tried quite a bit to the point where I'm at a loss. The following is my code: self.audioPlayer.allowsAirPlay = NO; Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter"); if (playingInfoCenter) { NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init]; MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"series_placeholder"]]; [songInfo setObject:thePodcast.title forKey:MPMediaItemPropertyTitle]; [songInfo setObject:thePodcast.author forKey:MPMediaItemPropertyArtist]; [songInfo setObject:@"NCC" forKey:MPMediaItemPropertyAlbumTitle]; [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork]; [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo]; } This isn't working, I've also tried: [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil]; In an attempt to get it to remove the existing information from the iPod app (or whatever may have info there). In addition, just to see if I could find out the problem, I've tried retrieving the current information on app launch: NSDictionary *info = [[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]; NSString *title = [info valueForKey:MPMediaItemPropertyTitle]; NSString *author = [info valueForKey:MPMediaItemPropertyArtist]; NSLog(@"Currently playing: %@ // %@", title, author); and I get Currently playing: (null) // (null) I've researched this quite a bit and the following articles explain it pretty thoroughly, however, I am still unable to get this working properly. Am I missing something? Would there be anything interfering with this? Is this a service something my app needs to register to access (didn't see this in any docs)? Apple's Docs Change lock screen background audio controls Now playing info ignored UPDATE: I've created a tutorial outlining how I was able to get this functioning properly: http://jaysonlane.net/tech-blog/2012/04/lock-screen-now-playing-with-mpnowplayinginfocenter/

    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

  • How do you clean Core Data generated models and code from a project?

    - by Hazmit
    I'm having an extremely annoying problem with Core Data in the iPhone SDK. I would say in general Core Data for the most part appears easy to use and nice to implement. I have a sqlite database that is being used as a read only reference to pull data elements out for an iPhone app. It would seem there are really mysterious issues relating to what seems to be migration of the database to the most recent versions of my schema. Why can't you just clean out your stored objects and models and let a project redo all of it when you compile next? You would think if you setup a stored object model there would be a way to just reset it and recompile. I've tried what feels like a thousand 'tips' that have been the results of hours of google searches and documentation prowling to figure out how to do this. My most recent error during compile time is below. 2010-04-07 18:23:51.891 PE[1962:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't merge models with two different entities named 'PElement'' All of this code has been working in the simulator and is only causing me troubles now because I made a change to the schema. I also have the database options for automatically migrating set as below. NSMutableDictionary *optionsDictionary = [NSMutableDictionary dictionary]; [optionsDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption]; [optionsDictionary setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

    Read the article

  • iPhone - openAL stops playing if I record with AVAudioRecorder

    - by Oscar Peli
    Hi there, this is an iPhone-related question: I use openAL to play some sound (I have to manage gain, pitch, etc.). I want to record what I'm playing and I use AVAudioRecorder but when I "prepareToRecord" openAL stops to play audio. What's the problem? Here is the record IBAction I use: - (IBAction) record: (id) sender { NSError *error; NSMutableDictionary *settings = [NSMutableDictionary dictionary]; [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey]; [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey]; [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; NSURL *url = [NSURL fileURLWithPath:FILEPATH]; self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; self.recorder.delegate = self; self.recorder.meteringEnabled = YES; [self.recorder prepareToRecord]; [self.recorder record]; } Thanks

    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

  • Why does Facebook iOS dialog for feed publish disappear after login?

    - by Mason G. Zhwiti
    I'm trying to use the Facebook iOS "feed" dialog call to allow my app's user to share something on their Facebook wall. When the facebook app is not installed, it attempts to let them authenticate within the app (presumably using a web view). The issue is that this dialog just disappears once they authenticate. I was expecting the web view to return to the "feed" sharing view. How do I detect that they authenticated so that I can re-open the feed dialog? I've added fbDidLogin to my app delegate, but it's not being called. (I wasn't sure if this would normally be called or not, but I read several people recommending this.) SBJSON *jsonWriter = [SBJSON new]; // The action links to be shown with the post in the feed NSArray* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys: @"More Videos",@"name",@"http://www.example.com/",@"link", nil], nil]; NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks]; NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Test Caption", @"caption", @"Test Description", @"description", @"https://s3.amazonaws.com/example/images/test.png", @"source", self.video.blogLink, @"link", @"01234567890123", @"app_id", actionLinksStr, @"actions", nil]; [delegate facebook].sessionDelegate = delegate; [[delegate facebook] dialog:@"feed" andParams:params andDelegate:self];

    Read the article

  • Custom Keyboard (iPhone), UIKeyboardDidShowNotification and UITableViewController

    - by Pascal
    On an iPhone App, I've got a custom keyboard which works like the standard keyboard; it appears if a custom textfield becomes first responder and hides if the field resigns first responder. I'm also posting the Generic UIKeyboardWillShowNotification, UIKeyboardDidShowNotification and their hiding counterparts, like follows: NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:5]; [userInfo setObject:[NSValue valueWithCGPoint:self.center] forKey:UIKeyboardCenterBeginUserInfoKey]; [userInfo setObject:[NSValue valueWithCGPoint:shownCenter] forKey:UIKeyboardCenterEndUserInfoKey]; [userInfo setObject:[NSValue valueWithCGRect:self.bounds] forKey:UIKeyboardBoundsUserInfoKey]; [userInfo setObject:[NSNumber numberWithInt:UIViewAnimationCurveEaseOut] forKey:UIKeyboardAnimationCurveUserInfoKey]; [userInfo setObject:[NSNumber numberWithDouble:thisAnimDuration] forKey:UIKeyboardAnimationDurationUserInfoKey]; [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:userInfo]; This code is working and I use it in UIViewController subclasses. Now since iPhone OS 3.0, UITableViewController automatically resizes its tableView when the system keyboards show and hide. I'm only now compiling against 3.0 and I thought that the controller should also resize the table if my custom keyboard appears, since I'm posting the same notification. However it doesn't. The table view controller is set as the delegate of the input fields. Does anyone have an idea why this might be the case? Has anyone implemented something similar successfully? I have standard input fields along the custom ones, so if the user changes the fields the standard keyboard hides and the custom one shows. It would be beneficial if the tableView didn't resize to full height and I didn't have to resize it back with a custom method.

    Read the article

  • EXC_BAD_ACCESS when executing ABAddressBookSave !

    - by Horatiu Paraschiv
    Hi everybody, I'm trying to create a new contact and add it to the AddressBook but when I get to the ABAddressSave line of code I get EXC_BAD_ACCESS. I cannot see what am I doing wrong, I enabled NSZombie to check if this is a memory related error but it didn't spot any. Can anybody tell me what is wrong with this code? Thank you in advance! CFErrorRef error = NULL; ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate(); ABRecordRef newRecord = ABPersonCreate(); ABRecordSetValue(newRecord, kABPersonFirstNameProperty, @"Xxxxxx", &error); ABRecordSetValue(newRecord, kABPersonURLProperty, @"Yyyyyy", &error); //Add phone numbers to record ABMutableMultiValueRef phones = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(phones, @"1-555-555-5555", kABWorkLabel, NULL); ABRecordSetValue(newRecord, kABPersonPhoneProperty, phones, &error); CFRelease(phones); //Add email address to record ABMutableMultiValueRef emails = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(emails, @"[email protected]", kABWorkLabel, NULL); ABRecordSetValue(newRecord, kABPersonEmailProperty, emails, &error); CFRelease(emails); ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); NSMutableDictionary *addressDict = [[NSMutableDictionary alloc] init]; [addressDict setObject:@"xxx1" forKey:(NSString *)kABPersonAddressStreetKey]; [addressDict setObject:@"xxx2" forKey:(NSString *)kABPersonAddressCityKey]; [addressDict setObject:@"xxx3" forKey:(NSString *)kABPersonAddressStateKey]; [addressDict setObject:@"xxx4" forKey:(NSString *)kABPersonAddressZIPKey]; ABMultiValueAddValueAndLabel(multiAddress, addressDict, kABWorkLabel, NULL); ABRecordSetValue(newRecord, kABPersonAddressProperty, multiAddress, &error); CFRelease(multiAddress); [addressDict release]; ABAddressBookAddRecord(iPhoneAddressBook, newRecord, &error); ABAddressBookSave(iPhoneAddressBook, NULL); if(error != nil){ NSLog(@"Error creating contact:%@", error); }

    Read the article

  • Cocoa Read NSInputStream from FTP connection

    - by Chuck
    Hi, I (apparently) manage to make a ftp connection, but fail to read anything from it, and with good cause: I don't reach the reading until the connection has timed out. Here's my code: NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; [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);forKey:NSStreamSocketSecurityLevelKey]; [iStream open]; [oStream retain]; [oStream setDelegate:self]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFWriteStreamSetProperty((CFWriteStreamRef)oStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); forKey:NSStreamSocketSecurityLevelKey]; [oStream open]; NSMutableData *returnMessage = [NSMutableData dataWithLength: 300]; [iStream read: [returnMessage mutableBytes] maxLength: 300]; NSString *readData = [[NSString alloc] initWithBytes: [returnMessage bytes] length: 300 encoding: NSUTF8StringEncoding]; NSRunAlertPanel(@"response", readData, nil, nil, nil); I have not sent a request to the FTP to switch to ssl yet. Any help is greatly appreciated as I find Xcode quite horrible for debugging (no exception or error msg on failed steps what so ever). Chuck

    Read the article

  • NSMutableArray of Objects

    - by Terry Owen
    First off I am very new to Objective C and iPhone programming. Now that that is out of the way. I have read through most of the Apple documentation on this and some third party manuals. I guess I just want to know if I'm going about this the correct way ... - (NSMutableArray *)makeModel { NSString *api = @"http://www.mycoolnewssite.com/api/v1"; NSArray *namesArray = [NSArray arrayWithObjects:@"News", @"Sports", @"Entertainment", @"Business", @"Features", nil]; NSArray *urlsArray = [NSArray arrayWithObjects: [NSString stringWithFormat:@"%@/news/news/25/stories.json", api], [NSString stringWithFormat:@"%@/news/sports/25/stories.json", api], [NSString stringWithFormat:@"%@/news/entertainment/25/stories.json", api], [NSString stringWithFormat:@"%@/news/business/25/stories.json", api], [NSString stringWithFormat:@"%@/news/features/25/stories.json", api], nil]; NSMutableArray *result = [NSMutableArray array]; for (int i = 0; i < [namesArray count]; i++) { NSMutableDictionary *objectDict = [NSMutableDictionary dictionary]; NSString *name = (NSString *)[namesArray objectAtIndex:i]; NSString *url = (NSString *)[urlsArray objectAtIndex:i]; [objectDict setObject:name forKey:@"NAME"]; [objectDict setObject:url forKey:@"URL"]; [objectDict setObject:@"NO" forKey:@"HASSTORIES"]; [result addObject:objectDict]; } return result; } Any insight would be appreciated ;-)

    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

  • Is this a good KVO-compliant way to model a mutable to-many relationship?

    - by andyvn22
    Say I'd like a mutable, unordered to-many relationship. For internal optimization reasons, it'd be best to store this in an NSMutableDictionary rather than an NSMutableSet. But I'd like to keep that implementation detail private. I'd also like to provide some KVO-compliant accessors, so: - (NSSet*)things; - (NSUInteger)countOfThings; - (void)addThings:(NSSet*)someThings; - (void)removeThings:(NSSet*)someThings; Now, it'd be convenient and less evil to provide accessors (private ones, of course, in my implementation file) for the dictionary as well, so: @interface MYClassWithThings () @property (retain) NSMutableDictionary* keyedThings; @end This seems good to me! I can use accessors to mess with my keyedThings within the class, but other objects think they're dealing with a mutable, unordered (, unkeyed!) to-many relationship. I'm concerned that several things I'm doing may be "evil" though, according to good style and Apple approval and whatnot. Have I done anything evil here? (For example, is it wrong not to provide setThings, since the things property is supposedly mutable?)

    Read the article

  • NSTimer to smooth out playback position

    - by Michael
    I have an audio player and I want to show the current time of the the playback. I'm using a custom play class. The app downloads the mp3 to a file then plays from the file when 5% has been downloaded. I have a progress view update as the file plays and update a label on each call to the progress view. However, this is jerky... sometimes even going backward a digit or two. I was considering using an NSTimer to smooth things out. I would be fired every second to a method and pass the percentage played figure to the method then update the label. First, does this seem reasonable? Second, how do I pass the percentage (a float) over to the target of the timer. Right now I am putting the percent played into a dictionary but this seems less than optimal. This is what is called update the progress bar: -(void)updateAudioProgress:(Percentage)percent { audio = percent; if (!seekChanging) slider.value = percent; NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init]; [myDictionary setValue:[NSNumber numberWithFloat:percent] forKey:@"myPercent"]; [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(myTimerMethod:) userInfo:myDictionary repeats:YES]; [myDictionary release]; } This is called first after 5 seconds but then updates each time the method is called. As always, comments and pointers appreciated.

    Read the article

  • NSMutableArray Problem - iPhone

    - by David Schiefer
    Hi, I'm trying to get a UITableView to read it's data from a file. I've attempted it like this: NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory]; self.dataForTable = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName]; This compiles fine, but when saving something to the file in the following snippet, the file is not saved nor anything is written to the array: NSMutableDictionary*userDictionary; userDictionary = [[NSMutableDictionary alloc] init]; [userDictionary setObject:name.text forKey:@"name"]; [userDictionary setObject:email.text forKey:@"email"]; [userDictionary setObject:serial.text forKey:@"serial"]; [userDictionary setObject:notes.text forKey:@"notes"]; [userDictionary setObject:[NSNumber numberWithInt:[licenseType selectedRowInComponent:0]] forKey:@"license_type"]; [userDictionary setObject:[date date] forKey:@"date"]; [userDictionary setObject:[NSNumber numberWithBool:[paymentSwitch isOn]] forKey:@"payment"]; NSString*dirToSaveTo = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSString*fileName = [NSString stringWithFormat:@"%@.plist",name.text]; NSString*saveName = [dirToSaveTo stringByAppendingPathComponent:fileName]; [userDictionary writeToFile:saveName atomically:NO]; NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory]; [self.dataForTable addObject:name.text]; NSLog(@"%@",self.dataForTable); [self.dataForTable writeToFile:fullFileName atomically:YES]; The NSLog just returns (null). The *plist file is never written. What am I doing wrong?

    Read the article

  • Several Objective-C objects become Invalid for no reason, sometimes.

    - by farnsworth
    - (void)loadLocations { NSString *url = @"<URL to a text file>"; NSStringEncoding enc = NSUTF8StringEncoding; NSString *locationString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url] usedEncoding:&enc error:nil]; NSArray *lines = [locationString componentsSeparatedByString:@"\n"]; for (int i=0; i<[lines count]; i++) { NSString *line = [lines objectAtIndex:i]; NSArray *components = [line componentsSeparatedByString:@", "]; Restaurant *res = [byID objectForKey:[components objectAtIndex:0]]; if (res) { NSString *resAddress = [components objectAtIndex:3]; NSArray *loc = [NSArray arrayWithObjects:[components objectAtIndex:1], [components objectAtIndex:2]]; [res.locationCoords setObject:loc forKey:resAddress]; } else { NSLog([[components objectAtIndex:0] stringByAppendingString:@" res id not found."]); } } } There are a few weird things happening here. First, at the two lines where the NSArray lines is used, this message is printed to the console- *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary count]: method sent to an uninitialized mutable dictionary object' which is strange since lines is definitely not an NSMutableDictionary, definitely is initialized, and because the app doesn't crash. Also, at random points in the loop, all of the variables that the debugger can see will become Invalid. Local variables, property variables, everything. Then after a couple lines they will go back to their original values. setObject:forKey never has an effect on res.locationCoords, which is an NSMutableDictionary. I'm sure that res, res.locationCoords, and byId are initialized. I also tried adding a retain or copy to lines, same thing. I'm sure there's a basic memory management principle I'm missing here but I'm at a loss.

    Read the article

  • Limit Annotation number in Mapkit

    - by teddafan
    Hi all, I want to stop my app from loading more annotations after they are all added ( they are added by the user one by one). How would you do that? the following code is what i think is important (void) loadAndSortPOIs { [poiArray release]; nextPoiIndex = 0; NSString *poiPath = [[NSBundle mainBundle] pathForResource:@"pois" ofType:@"plist"]; poiArray = [[NSMutableArray alloc] initWithContentsOfFile:poiPath]; CLLocation *homeLocation = [[CLLocation alloc] initWithLatitude:homeCoordinate.latitude longitude:homeCoordinate.longitude]; for (int i = 0; i < [poiArray count]; i++) { NSDictionary *dict = (NSDictionary*) [poiArray objectAtIndex: i]; CLLocationDegrees storeLatitude = [[dict objectForKey:@"workingCoordinate.latitude"] doubleValue]; CLLocationDegrees storeLongitude = [[dict objectForKey:@"workingCoordinate.longitude"] doubleValue]; CLLocation *storeLocation = [[CLLocation alloc] initWithLatitude:storeLatitude longitude:storeLongitude]; CLLocationDistance distanceFromHome = [storeLocation getDistanceFrom: homeLocation]; NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] initWithDictionary:dict]; [mutableDict setValue:[NSNumber numberWithDouble:distanceFromHome] forKey:@"distanceFromHome"]; [poiArray replaceObjectAtIndex:i withObject:mutableDict]; [mutableDict release]; } [homeLocation release]; // now sort by distanceFromHome NSArray *sortDescriptors = [NSArray arrayWithObject: [[NSSortDescriptor alloc] initWithKey: @"distanceFromHome" ascending: YES]]; [poiArray sortUsingDescriptors:sortDescriptors]; NSLog (@"poiArray: %@", poiArray); } Thank you for your help. Best regards,

    Read the article

  • EXC_BAD_ACCESS with NSUserdefaults on iphone.

    - by Andreas Johannessen
    I have the following code in my ApplicationDelegate. My deployment target is 3.0 and upwards, however I get a EXC_BAD_ACCESS when I launch the app with the following code on my iPhone with 3.1.3, however on the simulator which has 4.2 it runs fine. I would really appriciate help on this one, thanks in advance. When I comment this block when I deploy to 3.1.3 device it runs without bad access. + (void)initialize { NSString *path = [[NSBundle mainBundle] bundlePath]; NSString *pListPath = [path stringByAppendingPathComponent:@"Settings.bundle/Root.plist"]; NSDictionary *pList = [NSDictionary dictionaryWithContentsOfFile:pListPath]; NSMutableArray *prefsArray = [pList objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *regDictionary = [NSMutableDictionary dictionary]; for (NSDictionary *dict in prefsArray) { NSString *key = [dict objectForKey:@"Key"]; if(key) { id value = [dict objectForKey:@"DefaultValue"]; [regDictionary setObject:value forKey:key]; } } [[NSUserDefaults standardUserDefaults] registerDefaults:regDictionary]; } UPDATE: I traced the error to happen on this line: [[NSUserDefaults standardUserDefaults] registerDefaults:regDictionary]; So there is probaly another syntax on earlier iOS, or am I wrong?

    Read the article

  • How do I get Spotlight attributes to display in the get info window?

    - by Alexander Rauchfuss
    I have created a spotlight importer for comic files. The attributes are successfully imported and searchable. The one thing that remains is getting the attributes to display in a file's get info window. It seems that this should be a simple matter of editing the schema.xml file so the attributes are nested inside displayattrs tags. Unfortunately this does not seem to be working. I simplified the plugin for testing. The following are all of the important files. schema.xml <types> <type name="cx.c3.cbz-archive"> <allattrs> kMDItemTitle kMDItemAuthors </allattrs> <displayattrs> kMDItemTitle kMDItemAuthors </displayattrs> </type> <type name="cx.c3.cbr-archive"> <allattrs> kMDItemTitle kMDItemAuthors </allattrs> <displayattrs> kMDItemTitle kMDItemAuthors </displayattrs> </type> GetMetadataForFile.m Boolean GetMetadataForFile(void* thisInterface, CFMutableDictionaryRef attributes, CFStringRef contentTypeUTI, CFStringRef pathToFile) { NSAutoreleasePool * pool = [NSAutoreleasePool new]; NSString * file = (NSString *)pathToFile; NSArray * authors = [[UKXattrMetadataStore stringForKey: @"com_opencomics_authors" atPath: file traverseLink: NO] componentsSeparatedByString: @","]; [(NSMutableDictionary *)attributes setObject: authors forKey: (id)kMDItemAuthors]; NSString * title = [UKXattrMetadataStore stringForKey: @"com_opencomics_title" atPath: file traverseLink: NO]; [(NSMutableDictionary *)attributes setObject: title forKey: (id)kMDItemTitle]; [pool release]; return true; }

    Read the article

  • @selector and return value

    - by user320926
    The idea it's very easy, i have an http download class, this class must support the http authentication but it's basically a background thread so i would like to avoid to prompt directly to the screen, i would like to use a delegate method to require from outside of the class, like a viewController. But i don't know if is possible or if i have to use a different syntax. This class use this delegate protocol: //Updater.h @protocol Updater <NSObject> -(NSDictionary *)authRequired; @optional -(void)statusUpdate:(NSString *)newStatus; -(void)downloadProgress:(int)percentage; @end @interface Updater : NSThread { ... } This is the call to the delegate method: //Updater.m // This check always fails :( if ([self.delegate respondsToSelector:@selector(authRequired:)]) { auth = [delegate authRequired]; } This is the implementation of the delegate method //rootViewController.m -(NSDictionary *)authRequired; { // TODO: some kind of popup or modal view NSMutableDictionary *ret=[[NSMutableDictionary alloc] init]; [ret setObject:@"utente" forKey:@"user"]; [ret setObject:@"password" forKey:@"pass"]; return ret; }

    Read the article

  • Model class for NSDictionary information with Lazy Loading

    - by samfu_1
    My application utilizes approx. 50+ .plists that are used as NSDictionaries. Several of my view controllers need access to the properties of the dictionaries, so instead of writing duplicate code to retrieve the .plist, convert the values to a dictionary, etc, each time I need the info, I thought a model class to hold the data and supply information would be appropriate. The application isn't very large, but it does handle a good deal of data. I'm not as skilled in writing model classes that conform to the MVC paradigm, and I'm looking for some strategies for this implementation that also supports lazy loading.. This model class should serve to supply data to any view controller that needs it and perform operations on the data (such as adding entries to dictionaries) when requested by the controller functions currently planned: returning the count on any dictionary adding one or more dictionaries together Currently, I have this method for supporting the count lookup for any dictionary. Would this be an example of lazy loading? -(NSInteger)countForDictionary: (NSString *)nameOfDictionary { NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource: nameOfDictionary ofType: @"plist"]; //load plist into dictionary NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath]; NSInteger count = [dictionary count] [dictionary release]; [return count] }

    Read the article

  • Shuffle Two NSMutableArray independently

    - by Superman
    I'm creating two NSMutableArray in my viewDidLoad, I add it in a NSMutableDictionary. When I tried shuffling it with one array, It is okay. But the problem is when Im shuffling two arrays independently its not working,somehow the indexes got mixed up. Here is my code for my array (I have two of these): self.items1 = [NSMutableArray new]; for(int i = 0; i <= 100; i++) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"[Images%d.png", i]]; if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){ self.container = [[NSMutableDictionary alloc] init]; [container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:@"items1"]; [container setObject:[NSNumber numberWithInt:i] forKey:@"index1"]; [items1 addObject:container]; } } NSLog(@"Count : %d", [items1 count]); [items1 enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) { NSLog(@"%@ images at index %d", object, index); }]; then my shuffle code(Which I tried duplicating for the other array,but not working also): srandom(time(NULL)); NSUInteger count = [items1 count]; for (NSUInteger i = 0; i < count; ++i) { int nElements = count - i; int n = (random() % nElements) + i; [items1 exchangeObjectAtIndex:i withObjectAtIndex:n]; } How am I going to shuffle it using above code (or if you have other suggestions) with two arrays? Thanks My other problem is when I tries subclassing the class for the shuffle method or either use the above code, their index mixed. For example: Object: apple, ball, carrots, dog Indexes: 1 2 3 4 but in my View when shuffled: Object: carrots, apple, dog, balle Indexes: 2 4 1 3

    Read the article

  • Big trouble after app update. CoreData migration error

    - by MrBr
    this morning we had a big trouble with our iphone app. We had to even take it off the store. The thing is that we made real small changes to our xcdatamodel. We thought that the update process is automatically taking care about exchanging it the right way until we found out something like CoreData migration exists. We are using the UIManagedDocument to connect to the persistent store. How is it possible to exchange this file with the new one? While we were developing we just uninstalled the whole app from the device and then installed it again and everything worked. How can we simulate this process in the app store with updates? UPDATE I try to set the migration option like this _database = [[UIIManagedDocument alloc] init]; NSMutableDictionary *options = [[NSMutableDictionary alloc] init]; [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption], _database.persistentStoreOptions = options; but the app is still crashing with ** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'

    Read the article

  • Deleting from 2 arrays of dictionaries

    - by Matt Winters
    I have an array of dictionaries loaded from a plist (below) called arrayHistory. <plist version="1.0"> <array> <dict> <key>item</key> <string>1</string> <key>result</key> <string>8.1</string> <key>date</key> <date>2009-12-15T19:36:59Z</date> </dict> ... </array> </plist> I filter this array based on 'item' so that a second array, arrayHistoryDetail has the same structure as arrayHistory but only contains e.g. 'item's equal to '1'. These detail items are successfully displayed in a tableView. I then want to select an item from the tableView, and delete it from the tableView data source, arrayHistoryDetail (line 2 in the code below) - works, then I want to delete the item from the tableView itself (line 3 in the code below) - also works. My problem is that I also need to delete it from the original arrayHistory, so I tried the following: created a temporary dictionary as an ivar: NSMutableDictionary *tempDict; @property (nonatomic, retain) NSMutableDictionary *tempDict; Then my thinking was to make a copy in line 1 and remove it from the original array in line 4. 1 tempDict = [arrayHistoryDetail objectAtIndex: indexPath.row]; 2 [arrayHistoryDetail removeObjectAtIndex: indexPath.row]; 3 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 4 [arrayHistory removeObject:tempDict]; Didn't work. Could someone please guide me in the right direction. I'm thinking that tempDict is a pointer and that removeObject needs a copy? I don't know. Thanks.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >