Search Results

Search found 399 results on 16 pages for 'nsobject'.

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

  • Does my use of the strategy pattern violate the fundamental MVC pattern in iOS?

    - by Goodsquirrel
    I'm about to use the 'strategy' pattern in my iOS app, but feel like my approach violates the somehow fundamental MVC pattern. My app is displaying visual "stories", and a Story consists (i.e. has @properties) of one Photo and one or more VisualEvent objects to represent e.g. animated circles or moving arrows on the photo. Each VisualEvent object therefore has a eventType @property, that might be e.g. kEventTypeCircle or kEventTypeArrow. All events have things in common, like a startTime @property, but differ in the way they are being drawn on the StoryPlayerView. Currently I'm trying to follow the MVC pattern and have a StoryPlayer object (my controller) that knows about both the model objects (like Story and all kinds of visual events) and the view object StoryPlayerView. To chose the right drawing code for each of the different visual event types, my StoryPlayer is using a switch statement. @implementation StoryPlayer // (...) - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { switch (event.eventType) { case kEventTypeCircle: [self showCircleEvent:event onStoryPlayerView:storyPlayerView]; break; case kEventTypeArrow: [self showArrowDrawingEvent:event onStoryPlayerView:storyPlayerView]; break; // (...) } But switch statements for type checking are bad design, aren't they? According to Uncle Bob they lead to tight coupling and can and should almost always be replaced by polymorphism. Having read about the "Strategy"-Pattern in Head First Design Patterns, I felt this was a great way to get rid of my switch statement. So I changed the design like this: All specialized visual event types are now subclasses of an abstract VisualEvent class that has a showOnStoryPlayerView: method. @interface VisualEvent : NSObject - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView; // abstract Each and every concrete subclass implements a concrete specialized version of this drawing behavior method. @implementation CircleVisualEvent - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView { [storyPlayerView drawCircleAtPoint:self.position color:self.color lineWidth:self.lineWidth radius:self.radius]; } The StoryPlayer now simply calls the same method on all types of events. @implementation StoryPlayer - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { [event showOnStoryPlayerView:storyPlayerView]; } The result seems to be great: I got rid of the switch statement, and if I ever have to add new types of VisualEvents in the future, I simply create new subclasses of VisualEvent. And I won't have to change anything in StoryPlayer. But of cause this approach violates the MVC pattern since now my model has to know about and depend on my view! Now my controller talks to my model and my model talks to the view calling methods on StoryPlayerView like drawCircleAtPoint:color:lineWidth:radius:. But this kind of calls should be controller code not model code, right?? Seems to me like I made things worse. I'm confused! Am I completely missing the point of the strategy pattern? Is there a better way to get rid of the switch statement without breaking model-view separation?

    Read the article

  • iPhone: how to use performSelector:onThread:withObject:waitUntilDone: method?

    - by Michael Kessler
    Hi all, I am trying to use a separate thread for working with some API. The problem is that I am not able to use performSelector:onThread:withObject:waitUntilDone: method with a thread that I' instantiated for this. My code: @interface MyObject : NSObject { NSThread *_myThread; } @property(nonatomic, retain) NSThread *myThread; @end @implementation MyObject @synthesize myThread = _myThread; - (NSThread *)myThread { if (_myThread == nil) { NSThread *myThreadTemp = [[NSThread alloc] init]; [myThreadTemp start]; self. myThread = myThreadTemp; [myThreadTemp release]; } return _myThread; } - (id)init { if (self = [super init]) { [self performSelector:@selector(privateInit:) onThread:[self myThread] withObject:nil waitUntilDone:NO]; } return self; } - (void)privateInit:(id)object { NSLog(@"MyObject - privateInit start"); } - (void)dealloc { [_myThread release]; _myThread = nil; [super dealloc]; } @end "MyObject - privateInit start" is never printed. What am I missing? I tried to instantiate the thread with target and selector, tried to wait for method execution completion (waitUntilDone:YES). Nothing helps. UPDATE: I don't need this multithreading for separating costly operations to another thread. In this case I could use the performSelectorInBackground as mentioned in few answers. The main reason for this separate thread is the need to perform all the actions in the API (TTS by Loquendo) from one single thread. Meaning that I have to create an instance of the TTS object and call methods on that object from the same thread all the time.

    Read the article

  • Noob Objective-C/C++ - Linker Problem/Method Signature Problem

    - by Josh
    There is a static class Pipe, defined in C++ header that I'm including. The static method I'm interested in calling (from Objetive-c) is here: static ERC SendUserGet(const UserId &_idUser,const GUID &_idStyle,const ZoneId &_idZone,const char *_pszMsg); I have access to an objetive-c data structure that appears to store a copy of userID, and zoneID -- it looks like: @interface DataBlock : NSObject { GUID userID; GUID zoneID; } Looked up the GUID def, and its a struct with a bunch of overloaded operators for equality. UserId and ZoneId from the first function signature are #typedef GUID Now when I try to call the method, no matter how I cast it (const UserId), (UserId), etc, I get the following linker error: Ld build/Debug/Seeker.app/Contents/MacOS/Seeker normal i386 cd /Users/josh/Development/project/Mac/Seeker setenv MACOSX_DEPLOYMENT_TARGET 10.5 /Developer/usr/bin/g++-4.2 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk -L/Users/josh/Development/TS/Mac/Seeker/build/Debug -L/Users/josh/Development/TS/Mac/Seeker/../../../debug -L/Developer/Platforms/iPhoneOS.platform/Developer/usr/lib/gcc/i686-apple-darwin10/4.2.1 -F/Users/josh/Development/TS/Mac/Seeker/build/Debug -filelist /Users/josh/Development/TS/Mac/Seeker/build/Seeker.build/Debug/Seeker.build/Objects-normal/i386/Seeker.LinkFileList -mmacosx-version-min=10.5 -framework Cocoa -framework WebKit -lSAPI -lSPL -o /Users/josh/Development/TS/Mac/Seeker/build/Debug/Seeker.app/Contents/MacOS/Seeker Undefined symbols: "SocPipe::SendUserGet(_GUID const&, _GUID const&, _GUID const&, char const*)", referenced from: -[PeoplePaneController clickGet:] in PeoplePaneController.o ld: symbol(s) not found collect2: ld returned 1 exit status Is this a type/function signature error, or truly some sort of linker error? I have the headers where all these types and static classes are defined #imported -- I tried #include too, just in case, since I'm already stumbling :P Forgive me, I come from a web tech background, so this c-style memory management and immutability stuff is super hazy. Edit: Added full linker error text. Changed "function" to "method" Thanks, Josh

    Read the article

  • Noob Objective-C/C++ - Linker Problem/Function Def Problem

    - by Josh
    There is a static class Pipe, defined in C++ header that I'm including. The function I'm interested in calling (from Objetive-c) is here: static ERC SendUserGet(const UserId &_idUser,const GUID &_idStyle,const ZoneId &_idZone,const char *_pszMsg); I have access to an objetive-c data structure that appears to store a copy of userID, and zoneID -- it looks like: @interface DataBlock : NSObject { GUID userID; GUID zoneID; } Looked up the GUID def, and its a struct with a bunch of overloaded operators for equality. UserId and ZoneId from the first function signature are #typedef GUID Now when I try to call the function, no matter how I cast it (const UserId), (UserId), etc, I get the following linker error: "Pipe::SendUserGet(_GUID const&, _GUID const&, _GUID const&, char const*)", referenced from: -[PeoplePaneController clickGet:] in PeoplePaneController.o Is this a type/function signature error, or truly some sort of linker error? I have the headers where all these types and static classes are defined #imported -- I tried #include too, just in case, since I'm already stumbling :P Forgive me, I come from a web tech background, so this c-style memory management and immutability stuff is super hazy. Thanks, Josh

    Read the article

  • Ivar definitions show 'long' type encoding as 'long long' type encoding

    - by Frank C.
    I've found what I think may be a bug with Ivar and Objective-C runtime. I'm using XCode 3.2.1 and associated libraries, developing a 64 bit app on X86_64 (MacBook Pro). Where I would expect the type encoding for the following "longVal" to be 'l', the Ivar encoding is showing a 'q' (which is a 'long long'). Anyone else seeing this? Simplified code and output follows: Code: #import <Foundation/Foundation.h> #import <objc/runtime.h> @interface Bug : NSObject { long longVal; long long longerVal; } @property (nonatomic,assign) long longVal; @property (nonatomic,assign) long long longerVal; @end @implementation Bug @synthesize longVal,longerVal; @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int ivarCount=0; Ivar *ivars= class_copyIvarList([Bug class], &ivarCount); for(unsigned int x=0;x<ivarCount;x++) { NSLog(@"Name [%@] encoding [%@]", [NSString stringWithCString:ivar_getName(ivars[x]) encoding:NSUTF8StringEncoding], [NSString stringWithCString:ivar_getTypeEncoding(ivars[x]) encoding:NSUTF8StringEncoding]); } [pool drain]; return 0; } And here is output from debug console: This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000 Loading program into debugger… sharedlibrary apply-load-rules all Program loaded. run [Switching to process 6048] Running… 2010-03-17 22:16:29.138 ivarbug[6048:a0f] Name [longVal] encoding [q] 2010-03-17 22:16:29.146 ivarbug[6048:a0f] Name [longerVal] encoding [q] (gdb) continue Not a pretty picture! -- Frank

    Read the article

  • Random MKAnnotationView is tapped when there are overlapping annotations

    - by Alexandre Gellibert
    I cannot believe this bug/problem doesn't have any solution! In my iphone application, I'm using MapKit with MKMapView and custom MKAnnotationView. The problem is when annotations overlap (in my app, annotations are photos and those photos may overlap) and when you tap on the annotation that appears on front, other annotation (on back) receives the event (seems to be random). I didn't find any way to send the event to the front annotation. Z ordering and Order of overlapping annotations questions on stackoverflow did not help me that much. Please any idea is welcome (even ugly ones)! Here's some of my code (nothing fancy, very common): CustomAnnotation.h @interface CustomAnnotation : NSObject <MKAnnotation> { @private CustomAnnotationView* view; } @property (nonatomic, retain) CustomAnnotationView* view; @end CustomAnnotation.m @implementation CustomAnnotation @synthetize view; CustomAnnotationView.h @interface CustomAnnotationView : MKAnnotationView { } @end CustomAnnotationView.m @implementation CustomAnnotationView - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ // Do something related to the annotation tapped } @end Main class ... // Annotations are added and some of them overlaps with others. - (void)addAnnotation:(CustomAnnotation*)annotation { [map addAnnotation:annotation]; } ... - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { NSString* identifier = getIdentifierFromAnnotation(annotation); CustomAnnotationView* view; if(!(view = (CustomAnnotationView*)[map dequeueReusableAnnotationViewWithIdentifier:identifier])) { view = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: identifier]; [(CustomAnnotation*)annotation setView:view]; [view release]; } return view; }

    Read the article

  • How to get skin tone color pixel in iPhone?

    - by aman-gupta
    Hi In my application I m using following way to get red pixel in a image // // PixelsAccessAppDelegate.h // PixelsAccess // // Created by Fortune1 on 14/04/10. // Copyright MyCompanyName 2010. All rights reserved. // import @class clsPixelAccess; NSUInteger numberOfRedPixels; NSUInteger numberOfRedPixels1; NSUInteger numberOfRedPixels2; NSUInteger numberOfRedPixels3; NSUInteger numberOfRedPixels4; NSUInteger numberOfRedPixels5; NSUInteger numberOfRedPixels6; NSUInteger numberOfRedPixels7; NSUInteger numberOfRedPixels8; NSUInteger numberOfRedPixels9; NSUInteger numberOfRedPixels10; NSUInteger numberOfRedPixels11; NSUInteger numberOfRedPixels12; NSUInteger numberOfRedPixels13; NSUInteger numberOfRedPixels14; NSUInteger numberOfRedPixels15; NSUInteger numberOfRedPixels16; NSUInteger numberOfRedPixels17; NSUInteger numberOfRedPixels18; NSUInteger numberOfRedPixels19; NSUInteger numberOfRedPixels20; NSUInteger numberOfRedPixels21; NSUInteger numberOfRedPixels22; NSUInteger numberOfRedPixels23; NSUInteger numberOfRedPixels24; NSUInteger numberOfRedPixels25; NSUInteger numberOfRedPixels26; NSUInteger numberOfRedPixels27; NSUInteger numberOfRedPixels28; NSUInteger numberOfRedPixels29; NSUInteger numberOfRedPixels30; NSUInteger numberOfRedPixels31; @interface PixelsAccessAppDelegate : NSObject { UIWindow *window; clsPixelAccess *obj; } @property (nonatomic, retain) IBOutlet UIWindow *window; -(IBAction)processImage:(id)sender; @end //////////////////// // // PixelsAccessAppDelegate.m // PixelsAccess // // Created by Fortune1 on 14/04/10. // Copyright MyCompanyName 2010. All rights reserved. // import "PixelsAccessAppDelegate.h" import "clsPixelAccess.h" @implementation PixelsAccessAppDelegate @synthesize window; (IBAction)processImage:(id)sender { NSUInteger retVal; obj = [[clsPixelAccess alloc] init]; NSInteger imageSend =[obj processImage1:[UIImage imageNamed:@"s.jpg"]]; NSInteger iamgeCall =[obj getPixelData:retVal]; NSUInteger *numberOfRedPixels = retVal; //lblPixelCount.text = [NSString stringWithFormat: @"There are %d red pixels in the image", numberOfRedPixels]; } (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after application launch [window makeKeyAndVisible]; } (void)dealloc { [window release]; [super dealloc]; } @end /////////////// // // clsPixelsAccess.h // PixelsAccess // // Created by Fortune1 on 14/04/10. // Copyright 2010 MyCompanyName. All rights reserved. // import @interface clsPixelAccess : NSObject { } -(NSInteger) processImage1: (UIImage*) image; -(NSInteger)getPixelData:(NSUInteger *)pixelCount; @end ///////// // // clsPixelsAccess.m // PixelsAccess // // Created by Fortune1 on 14/04/10. // Copyright 2010 MyCompanyName. All rights reserved. // import "clsPixelAccess.h" import "PixelsAccessAppDelegate.h" @implementation clsPixelAccess struct pixel { //unsigned char r, g, b,a; Byte r, g, b, a; int count; }; -(NSInteger)getPixelData:(NSUInteger *)pixelCount { *pixelCount =numberOfRedPixels; return 1; } // Process the image and return the number of pure red pixels in it. (NSInteger) processImage1: (UIImage*) image { // Allocate a buffer big enough to hold all the pixels struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel)); if (pixels != nil) { // Create a new bitmap CGContextRef context = CGBitmapContextCreate( (void*) pixels, image.size.width, image.size.height, 8, image.size.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast ); //NSLog(@"1=%d, 2=%d, 3=%d", CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image),CGImageGetBytesPerRow(image)); if (context != NULL) { // Draw the image in the bitmap CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage); NSUInteger numberOfPixels = image.size.width * image.size.height; NSMutableArray *numberOfPixelsArray = [[[NSMutableArray alloc] initWithCapacity:numberOfPixelsArray] autorelease]; NSLog( @"Pixel data %d", numberOfPixelsArray); /* NSMatrix *newMatrix = [[NSMatrix alloc] initWithFrame:NSMakeRect(138.0f, 85.0f, 0.0f, 0.0f) mode:NSRadioModeMatrix prototype:prototypeButtonCell numberOfRows: numberOfColumns:]; */ while (numberOfPixels &gt; 0) { if (pixels-&gt;r &gt; 0 &amp;&amp; pixels-&gt;r &lt;= 7) { numberOfRedPixels++; } NSLog( @"Red pixel data %d",numberOfRedPixels); if (pixels-&gt;r &gt;= 8 &amp;&amp; pixels-&gt;r &lt;= 15) { numberOfRedPixels1++; } NSLog( @"Red pixel data1 %d",numberOfRedPixels1); if (pixels-&gt;r &gt;= 16 &amp;&amp; pixels-&gt;r &lt;=23 ) { numberOfRedPixels2++; } NSLog( @"Red pixel data2 %d",numberOfRedPixels2); if (pixels-&gt;r &gt;= 24 &amp;&amp; pixels-&gt;r &lt;=31 ) { numberOfRedPixels3++; } NSLog( @"Red pixel data3 %d",numberOfRedPixels3); if (pixels-&gt;r &gt;= 32 &amp;&amp; pixels-&gt;r &lt;= 39) { numberOfRedPixels4++; } NSLog( @"Red pixel data4 %d",numberOfRedPixels4); if (pixels-&gt;r &gt;= 40 &amp;&amp; pixels-&gt;r &lt;= 47) { numberOfRedPixels5++; } NSLog( @"Red pixel data5 %d",numberOfRedPixels5); if (pixels-&gt;r &gt;= 48 &amp;&amp; pixels-&gt;r &lt;= 55) { numberOfRedPixels6++; } NSLog( @"Red pixel data6 %d",numberOfRedPixels6); if(pixels-&gt;r &gt;= 56 &amp;&amp; pixels-&gt;r &lt;= 63) { numberOfRedPixels7++; } NSLog( @"Red pixel data7 %d",numberOfRedPixels7); if (pixels-&gt;r &gt;= 64 &amp;&amp; pixels-&gt;r &lt;= 71) { numberOfRedPixels8++; } NSLog( @"Red pixel data8 %d",numberOfRedPixels8); if (pixels-&gt;r &gt;= 72 &amp;&amp; pixels-&gt;r &lt;= 79) { numberOfRedPixels9++; } NSLog( @"Red pixel data9 %d",numberOfRedPixels9); if (pixels-&gt;r &gt;= 80 &amp;&amp; pixels-&gt;r &lt;= 87) { numberOfRedPixels10++; } NSLog( @"Red pixel data10 %d",numberOfRedPixels10); if (pixels-&gt;r &gt;= 88 &amp;&amp; pixels-&gt;r &lt;= 95) { numberOfRedPixels11++; } NSLog( @"Red pixel data11 %d",numberOfRedPixels11); if (pixels-&gt;r &gt;= 96 &amp;&amp; pixels-&gt;r &lt;= 103) { numberOfRedPixels12++; } NSLog( @"Red pixel data12 %d",numberOfRedPixels12); if (pixels-&gt;r &gt;= 104 &amp;&amp; pixels-&gt;r &lt;= 111) { numberOfRedPixels13++; } NSLog( @"Red pixel data13 %d",numberOfRedPixels13); if (pixels-&gt;r &gt;= 112 &amp;&amp; pixels-&gt;r &lt;= 119) { numberOfRedPixels14++; } NSLog( @"Red pixel data14 %d",numberOfRedPixels14); if (pixels-&gt;r &gt;= 120 &amp;&amp; pixels-&gt;r &lt;= 127) { numberOfRedPixels15++; } NSLog( @"Red pixel data15 %d",numberOfRedPixels15); if (pixels-&gt;r &gt; 128 &amp;&amp; pixels-&gt;r &lt;= 135) { numberOfRedPixels16++; } NSLog( @"Red pixel data16 %d",numberOfRedPixels16); if (pixels-&gt;r &gt;= 136 &amp;&amp; pixels-&gt;r &lt;= 143) { numberOfRedPixels17++; } NSLog( @"Red pixel data17 %d",numberOfRedPixels17); if (pixels-&gt;r &gt;= 144 &amp;&amp; pixels-&gt;r &lt;=151) { numberOfRedPixels18++; } NSLog( @"Red pixel data18 %d",numberOfRedPixels18); if (pixels-&gt;r &gt;= 152 &amp;&amp; pixels-&gt;r &lt;=159 ) { numberOfRedPixels19++; } NSLog( @"Red pixel data19 %d",numberOfRedPixels19); if (pixels-&gt;r &gt;= 160 &amp;&amp; pixels-&gt;r &lt;= 167) { numberOfRedPixels20++; } NSLog( @"Red pixel data20 %d",numberOfRedPixels20); if (pixels-&gt;r &gt;= 168 &amp;&amp; pixels-&gt;r &lt;= 175) { numberOfRedPixels21++; } NSLog( @"Red pixel data21 %d",numberOfRedPixels21); if (pixels-&gt;r &gt;= 176 &amp;&amp; pixels-&gt;r &lt;= 199) { numberOfRedPixels22++; } NSLog( @"Red pixel data22 %d",numberOfRedPixels22); if(pixels-&gt;r &gt;= 184 &amp;&amp; pixels-&gt;r &lt;= 191) { numberOfRedPixels23++; } NSLog( @"Red pixel data23 %d",numberOfRedPixels23); if (pixels-&gt;r &gt;= 192 &amp;&amp; pixels-&gt;r &lt;= 199) { numberOfRedPixels24++; } NSLog( @"Red pixel data24 %d",numberOfRedPixels24); if (pixels-&gt;r &gt;= 200 &amp;&amp; pixels-&gt;r &lt;= 207) { numberOfRedPixels25++; } NSLog( @"Red pixel data25 %d",numberOfRedPixels25); if (pixels-&gt;r &gt;= 208 &amp;&amp; pixels-&gt;r &lt;= 215) { numberOfRedPixels26++; } NSLog( @"Red pixel data26 %d",numberOfRedPixels26); if (pixels-&gt;r &gt;= 216 &amp;&amp; pixels-&gt;r &lt;= 223) { numberOfRedPixels27++; } NSLog( @"Red pixel data27 %d",numberOfRedPixels27); if (pixels-&gt;r &gt;= 224 &amp;&amp; pixels-&gt;r &lt;= 231) { numberOfRedPixels28++; } NSLog( @"Red pixel data28 %d",numberOfRedPixels28); if (pixels-&gt;r &gt;= 232 &amp;&amp; pixels-&gt;r &lt;= 239) { numberOfRedPixels29++; } NSLog( @"Red pixel data29 %d",numberOfRedPixels29); if (pixels-&gt;r &gt;= 240 &amp;&amp; pixels-&gt;r &lt;= 247) { numberOfRedPixels30++; } NSLog( @"Red pixel data30 %d",numberOfRedPixels30); if (pixels-&gt;r &gt;= 248) { numberOfRedPixels31++; } NSLog( @"Red pixel data31 %d",numberOfRedPixels31); pixels++; numberOfPixels--; } CGContextRelease(context); } free(pixels); } return 1; } @end My problem is I want skin Tone Pixel how it could be possible Please help me out. Thanks in Advance

    Read the article

  • MFMailComposeController crashing non-deterministically

    - by sss
    Hello, I've been struggling with this issue for a few days. I am trying to use the MFMailComposeController to send emails. What's happening is that the program crashes (long stack-trace below) upon clicking the SEND button. However, this is non-deterministic - sometimes it works immediately, sometimes after a long delay, and most often, it crashes. Here's my code for sending: -(void)mailWithAttachment:(NSString *) fileName type:(NSString*) attachmentType data:(NSData *) attachmentData { MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self; if ([MFMailComposeViewController canSendMail]) { [mc setSubject:@"my subject"]; [mc setMessageBody:@"my body" isHTML:YES]; [mc addAttachmentData:attachmentData mimeType:attachmentType fileName:fileName]; [self presentModalViewController:mc animated:YES]; } [mc release]; } didFinish result looks like you'd imagine: -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error { [self dismissModalViewControllerAnimated:YES]; //...some other actions here for other UI logic, but problem persists if removed } And the definition of the class: @interface ShareViewController : UIViewController { //... } Here's the stack trace: #0 0x33568534 in gdb_objc_debuggerModeFailure #1 0x3356634e in _rwlock_write_nodebug #2 0x33560940 in map_images #3 0x2fe0413e in __dyld__ZN4dyldL18notifyBatchPartialE17dyld_image_statesbPFPKcS0_jPK15dyld_image_infoE #4 0x2fe042d4 in __dyld__ZN4dyldL11notifyBatchE17dyld_image_states #5 0x2fe0aee0 in __dyld__ZN11ImageLoader4linkERKNS_11LinkContextEbbRKNS_10RPathChainE #6 0x2fe062d6 in __dyld__ZN4dyld4linkEP11ImageLoaderbRKNS0_10RPathChainE #7 0x2fe08188 in __dyld_dlopen #8 0x30c18fd0 in dlopen #9 0x0000390c in <function called from gdb> #10 0x3356628e in getMethodNoSuper_nolock #11 0x335662b8 in _class_getMethodNoSuper_nolock #12 0x3356518a in lookUpMethod #13 0x33562914 in _class_lookupMethodAndLoadCache #14 0x3356264a in objc_msgSend_uncached #15 0x33562a2a in _class_initialize #16 0x33567dfe in prepareForMethodLookup #17 0x33565168 in lookUpMethod #18 0x33562914 in _class_lookupMethodAndLoadCache #19 0x3356264a in objc_msgSend_uncached #20 0x32b2c288 in +[NSTimeZone(NSTimeZone) defaultTimeZone] #21 0x32b2c246 in -[NSCalendarDate initWithTimeIntervalSinceReferenceDate:] #22 0x32b3beb4 in -[NSDate(NSCalendarDateStuff) descriptionWithCalendarFormat:timeZone:locale:] #23 0x323642fc in -[NSDate(Goodies) descriptionForMimeHeaders] #24 0x32a6e812 in -[MailComposeController headersUseSuspendInfo:] #25 0x32a71e38 in -[MailComposeController messageUseSuspendInfo:endingEditing:] #26 0x32a6e594 in -[MailComposeController _getMessage:] #27 0x32a6e536 in -[MailComposeController message] #28 0x32a72bcc in -[MailComposeController deliverMessageRemotely] #29 0x32a7cab0 in -[_MFMailComposeRootViewController mailComposeControllerCompositionFinished:] #30 0x32a6e0a0 in -[MailComposeController sendMessage] #31 0x32a7086a in -[MailComposeController send:] #32 0x32c29ffa in -[NSObject performSelector:withObject:] #33 0x32a661cc in -[MailComposeView _sendButtonClicked:] I've tried the MFMailComposeController as a child of different views with the same result. Can anyone advise? I'd really appreciate it!

    Read the article

  • Objective-C classes, pointers to primitive types, etc.

    - by Toby Wilson
    I'll cut a really long story short and give an example of my problem. Given a class that has a pointer to a primitive type as a property: @interface ClassOne : NSObject { int* aNumber } @property int* aNumber; The class is instantiated, and aNumber is allocated and assigned a value, accordingly: ClassOne* bob = [[ClassOne alloc] init]; bob.aNumber = malloc(sizeof(int)); *bob.aNumber = 5; It is then passed, by reference, to assign the aNumber value of a seperate instance of this type of class, accordingly: ClassOne* fred = [[ClassOne alloc] init]; fred.aNumber = bob.aNumber; Fred's aNumber pointer is then freed, reallocated, and assigned a new value, for example 7. Now, the problem I'm having; Since Fred has been assigned the same pointer that Bob had, I would expect that Bob's aNumber will now have a value of 7. It doesn't, because for some reason it's pointer was freed, but not reassigned (it is still pointing to the same address it was first allocated which is now freed). Fred's pointer, however, has the allocated value 7 in a different memory location. Why is it behaving like this? What am I minsunderstanding? How can I make it work like C++ does?

    Read the article

  • iPhone UnitTesting UITextField value and otest error 133

    - by Justin Galzic
    Are UITextFields not meant to be part of the LogicTests and instead part of the ApplicationTest target? I have a factory class that is responsible for creating and returning an (iPhone) UITextField and I'm trying to unit test it. It is part of my Logic Test target and when I try to build and run the tests, I get a build error about: /Developer/Tools/RunPlatformUnitTests.include:451:0 Test rig '/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ 'Developer/usr/bin/otest' exited abnormally with code 133 (it may have crashed). In the build window, this points to the following line in: "RunPlatformUnitTests.include" RPUTIFail ${LINENO} "Test rig '${TEST_RIG}' exited abnormally with code ${TEST_RIG_RESULT} (it may have crashed)." My unit test looks like this: #import <SenTestingKit/SenTestingKit.h> #import <UIKit/UIKit.h> // Test-subject headers. #import "TextFieldFactory.h" @interface TextFieldFactoryTests : SenTestCase { } @end @implementation TextFieldFactoryTests #pragma mark Test Setup/teardown - (void) setUp { NSLog(@"%@ setUp", self.name); } - (void) tearDown { NSLog(@"%@ tearDown", self.name); } #pragma mark Tests - (void) testUITextField_NotASecureField { NSLog(@"%@ start", self.name); UITextField *textField = [TextFieldFactory createTextField:YES]; NSLog(@"%@ end", self.name); } The class I'm trying to test: // Header file #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface TextFieldFactory : NSObject { } +(UITextField *)createTextField:(BOOL)isSecureField; @end // Implementation file #import "TextFieldFactory.h" @implementation TextFieldFactory +(UITextField *)createTextField:(BOOL)isSecureField { // x,y,z,w are constants declared else where UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(x, y, z, w)] autorelease]; // some initialization code return textField; } @end

    Read the article

  • NSCollectionView subclass doesn't call drawRect during drag session despite setNeedsDisplay

    - by Alain Vitry
    Greetings, I am puzzled as to how and when drawRect is supposed to be called in a NSCollectionView subclass. I implement drag and drop operation in order to move NSCollectionViewItems within the collection, and would like to draw a visual indication of where the drop would end. The subclass does not call drawRect during the drag session. (It does during scroll) Is this the intended operation ? Any hint on how to implement this behavior properly are welcome. A full xcode project of the following code is available at: http://babouk.ovh.org/dload/MyCollectionView.zip Best regards Code sample: @interface CollectionViewAppDelegate : NSObject <NSApplicationDelegate> { NSWindow *window; NSMutableArray *collectionContent; } /* properties declaration */ /* KVC compliance declarations */ @end @interface MyCollectionView : NSCollectionView @end @interface ItemModel { NSString *name; } @property (copy) NSString *name; @end @implementation MyCollectionView - (void)drawRect:(NSRect)rect { NSLog(@"DrawRect"); } - (void)mouseDragged:(NSEvent *)aEvent { NSPoint localPoint = [self convertPoint:[aEvent locationInWindow] fromView:nil]; [self dragImage:[NSImage imageNamed:@"Move.png"] at:localPoint offset:NSZeroSize event:aEvent pasteboard:nil source:self slideBack:NO]; } - (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender { return YES; } - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender { return NSDragOperationEvery; } - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender { [self setNeedsDisplay:YES]; return NSDragOperationEvery; } - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal { return NSDragOperationEvery; } - (void)mouseDown:(NSEvent *)theEvent { } @end @implementation CollectionViewAppDelegate @synthesize window, collectionContent, collectionView; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSMutableArray *data = [[NSMutableArray alloc] init]; /* Fill in data */ [self setCollectionContent:data]; [data release]; } /* dealloc */ /* KVC implementation */ @end @implementation ItemModel @synthesize name; /* dealloc */ @end

    Read the article

  • OCUnit & NSBundle

    - by kpower
    I created OCUnit test in concordance with "iPhone Development Guide". Here is the class I want to test: // myClass.h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface myClass : NSObject { UIImage *image; } @property (readonly) UIImage *image; - (id)initWithIndex:(NSUInteger)aIndex; @end // myClass.m #import "myClass.m" @implementation myClass @synthesize image; - (id)init { return [self initWithIndex:0]; } - (id)initWithIndex:(NSUInteger)aIndex { if ((self = [super init])) { NSString *name = [[NSString alloc] initWithFormat:@"image_%i", aIndex]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"]; image = [[UIImage alloc] initWithContentsOfFile:path]; if (nil == image) { @throw [NSException exceptionWithName:@"imageNotFound" reason:[NSString stringWithFormat:@"Image (%@) with path \"%@\" for current index (%i) wasn't found.", [name autorelease], path, aIndex] userInfo:nil]; } [path release]; } return self; } - (void)dealloc { [image release]; [super dealloc]; } @end And my unit-test (LogicTests target): // myLogic.m #import <SenTestingKit/SenTestingKit.h> #import <UIKit/UIKit.h> #import "myClass.h" @interface myLogic : SenTestCase { } - (void)testTemp; @end @implementation myLogic - (void)testTemp { STAssertNoThrow([[myClass alloc] initWithIndex:0], "myClass initialization error"); } @end All necessary frameworks, "myClass.m" and images added to target. But on build I have an error: [[myClass alloc] initWithIndex:0] raised Image (image_0) with path \"(null)\" for current index (0) wasn't found.. myClass initialization error This code (initialization) works fine in application itself (main target) and later displays correct image. I've also checked my project folder (build/Debug-iphonesimulator/LogicTests.octest/) - there are LogicTests, Info.plist and necessary image files (image_0.png is one of them). What's wrong?

    Read the article

  • Multithreaded search with UISearchDisplayController

    - by Kulpreet
    I'm sort of new to any sort of multithreading and simply can't seem to get a simple search method working on a background thread properly. Everything seems to be in order with an NSAutoreleasePool and the UI being updated on the main thread. The app doesn't crash and does perform a search in the background but the search results yield the several of the same items several times depending on how fast I type it in. The search works properly without the multithreading (which is commented out), but is very slow because of the large amounts of data I am working with. Here's the code: - (void)filterContentForSearchText:(NSString*)searchText { NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init]; isSearching = YES; //[self.filteredListContent removeAllObjects]; // First clear the filtered array. for (Entry *entry in appDelegate.entries) { NSComparisonResult result = [entry.item compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.filteredListContent addObject:entry]; } } isSearching=NO; [self.searchDisplayController.searchResultsTableView performSelectorOnMainThread:(@selector(reloadData)) withObject:nil waitUntilDone:NO]; //[self.searchDisplayController.searchResultsTableView reloadData]; [apool drain]; } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(filteredListContent:) object:searchString]; [self.filteredListContent removeAllObjects]; // First clear the filtered array. [self performSelectorInBackground:(@selector(filterContentForSearchText:)) withObject:searchString]; //[self filterContentForSearchText:searchString]; // Return YES to cause the search result table view to be reloaded. return NO; }

    Read the article

  • Crash: iPhone Threading with Blocks

    - by jtbandes
    I have some convenience methods set up for threading with blocks (using PLBlocks). Then in the main portion of my code, I call the method -fetchArrivalsForLocationIDs:callback:errback:, which runs some web API calls in the background. Here's the problem: when I comment out the 2 NSAutoreleasePool-related lines in JTBlockThreading.m, of course I get lots of Object 0x6b31280 of class __NSArrayM autoreleased with no pool in place - just leaking errors. However, if I uncomment them, the app frequently crashes on the [pool release]; line, sometimes saying malloc: *** error for object 0x6e3ae10: pointer being freed was not allocated" *** set a breakpoint in malloc_error_break to debug. I assume I've made a horrible mistake/assumption in threading somewhere, but can anyone figure out what exactly the problem is? // JTBlockThreading.h #import <Foundation/Foundation.h> #import <PLBlocks/Block.h> #define JT_BLOCKTHREAD_BACKGROUND [self invokeBlockInBackground:^{ #define JT_BLOCKTHREAD_MAIN [self invokeBlockOnMainThread:^{ #define JT_BLOCKTHREAD_END }]; #define JT_BLOCKTHREAD_BACKGROUND_END_WAIT } waitUntilDone:YES]; @interface NSObject (JTBlockThreading) - (void)invokeBlockInBackground:(void (^)())block; - (void)invokeBlockOnMainThread:(void (^)())block; - (void)invokeBlockOnMainThread:(void (^)())block waitUntilDone:(BOOL)wait; - (void)invokeBlock:(void (^)())block; @end // JTBlockThreading.m #import "JTBlockThreading.h" @implementation NSObject (JTBlockThreading) - (void)invokeBlockInBackground:(void (^)())block { [self performSelectorInBackground:@selector(invokeBlock:) withObject:[block copy]]; } - (void)invokeBlockOnMainThread:(void (^)())block { [self invokeBlockOnMainThread:block waitUntilDone:NO]; } - (void)invokeBlockOnMainThread:(void (^)())block waitUntilDone:(BOOL)wait { [self performSelectorOnMainThread:@selector(invokeBlock:) withObject:[block copy] waitUntilDone:wait]; } - (void)invokeBlock:(void (^)())block { //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; block(); [block release]; //[pool release]; } @end - (void)fetchArrivalsForLocationIDs:(NSString *)locIDs callback:(JTWSCallback)callback errback:(JTWSErrback)errback { JT_PUSH_NETWORK(); JT_BLOCKTHREAD_BACKGROUND NSError *error = nil; // Create API call URL NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@/arrivals/appID/%@/locIDs/%@", TRIMET_BASE_URL, appID, locIDs]]; if (!url) { JT_BLOCKTHREAD_MAIN errback(@"That’s not a valid Stop ID!"); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } // Call API NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error]; if (!data) { JT_BLOCKTHREAD_MAIN errback([NSString stringWithFormat: @"Had trouble downloading the arrival data! %@", [error localizedDescription]]); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } CXMLDocument *doc = [[CXMLDocument alloc] initWithData:data options:0 error:&error]; if (!doc) { JT_BLOCKTHREAD_MAIN // TODO: further error description // (TouchXML doesn't provide information with the error) errback(@"Had trouble reading the arrival data!"); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } NSArray *nodes = nil; CXMLElement *resultSet = [doc rootElement]; // Begin building the response model JTWSResponseArrivalData *response = [[[JTWSResponseArrivalData alloc] init] autorelease]; response.queryTime = [NSDate JT_dateWithTriMetWSTimestamp: [[resultSet attributeValueForName:@"queryTime"] longLongValue]]; if (!response.queryTime) { // TODO: further error check? NSLog(@"Hm, query time is nil in %s... response %@, resultSet %@", __PRETTY_FUNCTION__, response, resultSet); } nodes = [resultSet nodesForXPath:@"//arrivals:errorMessage" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] > 0) { NSString *message = [[nodes objectAtIndex:0] stringValue]; response.errorMessage = message; // TODO: this probably won't be used... JT_BLOCKTHREAD_MAIN errback([NSString stringWithFormat: @"TriMet error: “%@”", message]); JT_POP_NETWORK(); JT_BLOCKTHREAD_END return; } // Build location models nodes = [resultSet nodesForXPath:@"/arrivals:location" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] <= 0) { NSLog(@"Hm, no locations returned in %s... xpath error %@, response %@, resultSet %@", __PRETTY_FUNCTION__, error, response, resultSet); } NSMutableArray *locations = [NSMutableArray arrayWithCapacity:[nodes count]]; for (CXMLElement *loc in nodes) { JTWSLocation *location = [[[JTWSLocation alloc] init] autorelease]; location.desc = [loc attributeValueForName:@"desc"]; location.dir = [loc attributeValueForName:@"dir"]; location.position = [[[CLLocation alloc] initWithLatitude:[[loc attributeValueForName:@"lat"] doubleValue] longitude:[[loc attributeValueForName:@"lng"] doubleValue]] autorelease]; location.locID = [[loc attributeValueForName:@"locid"] integerValue]; } // Build arrival models nodes = [resultSet nodesForXPath:@"/arrivals:arrival" namespaceMappings:namespaceMappings error:&error]; if ([nodes count] <= 0) { NSLog(@"Hm, no arrivals returned in %s... xpath error %@, response %@, resultSet %@", __PRETTY_FUNCTION__, error, response, resultSet); } NSMutableArray *arrivals = [[NSMutableArray alloc] initWithCapacity:[nodes count]]; for (CXMLElement *arv in nodes) { JTWSArrival *arrival = [[JTWSArrival alloc] init]; arrival.block = [[arv attributeValueForName:@"block"] integerValue]; arrival.piece = [[arv attributeValueForName:@"piece"] integerValue]; arrival.locID = [[arv attributeValueForName:@"locid"] integerValue]; arrival.departed = [[arv attributeValueForName:@"departed"] boolValue]; // TODO: verify arrival.detour = [[arv attributeValueForName:@"detour"] boolValue]; // TODO: verify arrival.direction = (JTWSRouteDirection)[[arv attributeValueForName:@"dir"] integerValue]; arrival.estimated = [NSDate JT_dateWithTriMetWSTimestamp: [[arv attributeValueForName:@"estimated"] longLongValue]]; arrival.scheduled = [NSDate JT_dateWithTriMetWSTimestamp: [[arv attributeValueForName:@"scheduled"] longLongValue]]; arrival.fullSign = [arv attributeValueForName:@"fullSign"]; arrival.shortSign = [arv attributeValueForName:@"shortSign"]; NSString *status = [arv attributeValueForName:@"status"]; if ([status isEqualToString:@"estimated"]) { arrival.status = JTWSArrivalStatusEstimated; } else if ([status isEqualToString:@"scheduled"]) { arrival.status = JTWSArrivalStatusScheduled; } else if ([status isEqualToString:@"delayed"]) { arrival.status = JTWSArrivalStatusDelayed; } else if ([status isEqualToString:@"canceled"]) { arrival.status = JTWSArrivalStatusCanceled; } else { NSLog(@"Unknown arrival status %s in %@... response %@, arrival %@", status, __PRETTY_FUNCTION__, response, arv); } NSArray *blockPositions = [arv nodesForXPath:@"/arrivals:blockPosition" namespaceMappings:namespaceMappings error:&error]; if ([blockPositions count] > 1) { // The schema allows for any number of blockPosition elements, // but I'm really not sure why... NSLog(@"Hm, more than one blockPosition in %s... response %@, arrival %@", __PRETTY_FUNCTION__, response, arv); } if ([blockPositions count] > 0) { CXMLElement *bpos = [blockPositions objectAtIndex:0]; JTWSBlockPosition *blockPosition = [[JTWSBlockPosition alloc] init]; blockPosition.reported = [NSDate JT_dateWithTriMetWSTimestamp: [[bpos attributeValueForName:@"at"] longLongValue]]; blockPosition.feet = [[bpos attributeValueForName:@"feet"] integerValue]; blockPosition.position = [[[CLLocation alloc] initWithLatitude:[[bpos attributeValueForName:@"lat"] doubleValue] longitude:[[bpos attributeValueForName:@"lng"] doubleValue]] autorelease]; NSString *headingStr = [bpos attributeValueForName:@"heading"]; if (headingStr) { // Valid CLLocationDirections are > 0 CLLocationDirection heading = [headingStr integerValue]; while (heading < 0) heading += 360.0; blockPosition.heading = heading; } else { blockPosition.heading = -1; // indicates invalid heading } NSArray *tripData = [bpos nodesForXPath:@"/arrivals:trip" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *trips = [[NSMutableArray alloc] initWithCapacity:[tripData count]]; for (CXMLElement *tripDatum in tripData) { JTWSTrip *trip = [[JTWSTrip alloc] init]; trip.desc = [tripDatum attributeValueForName:@"desc"]; trip.destDist = [[tripDatum attributeValueForName:@"destDist"] integerValue]; trip.direction = (JTWSRouteDirection)[[tripDatum attributeValueForName:@"dir"] integerValue]; trip.pattern = [[tripDatum attributeValueForName:@"pattern"] integerValue]; trip.progress = [[tripDatum attributeValueForName:@"progress"] integerValue]; trip.route = [[tripDatum attributeValueForName:@"route"] integerValue]; [trips addObject:trip]; [trip release]; } blockPosition.trips = trips; [trips release]; NSArray *layoverData = [bpos nodesForXPath:@"/arrivals:layover" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *layovers = [[NSMutableArray alloc] initWithCapacity:[layoverData count]]; for (CXMLElement *layoverDatum in layoverData) { JTWSLayover *layover = [[JTWSLayover alloc] init]; layover.start = [NSDate JT_dateWithTriMetWSTimestamp: [[layoverDatum attributeValueForName:@"start"] longLongValue]]; layover.end = [NSDate JT_dateWithTriMetWSTimestamp: [[layoverDatum attributeValueForName:@"end"] longLongValue]]; // TODO: it seems the API can send a <location> inside a layover (undocumented)... support? [layovers addObject:layover]; [layover release]; } blockPosition.layovers = layovers; [layovers release]; arrival.blockPosition = blockPosition; [blockPosition release]; } [arrivals addObject:arrival]; [arrival release]; } // Add arrivals to corresponding locations for (JTWSLocation *loc in locations) { loc.arrivals = [arrivals selectWithBlock:^BOOL (id arv) { return loc.locID == ((JTWSArrival *)arv).locID; }]; } [arrivals release]; response.locations = locations; [locations release]; // Build route status models (used in inclement weather) nodes = [resultSet nodesForXPath:@"/arrivals:routeStatus" namespaceMappings:namespaceMappings error:&error]; NSMutableArray *routeStatuses = [NSMutableArray arrayWithCapacity:[nodes count]]; for (CXMLElement *stat in nodes) { JTWSRouteStatus *status = [[JTWSRouteStatus alloc] init]; status.route = [[stat attributeValueForName:@"route"] integerValue]; NSString *statusStr = [stat attributeValueForName:@"status"]; if ([statusStr isEqualToString:@"estimatedOnly"]) { status.status = JTWSRouteStatusTypeEstimatedOnly; } else if ([statusStr isEqualToString:@"off"]) { status.status = JTWSRouteStatusTypeOff; } else { NSLog(@"Unknown route status type %s in %@... response %@, routeStatus %@", status, __PRETTY_FUNCTION__, response, stat); } [routeStatuses addObject:status]; [status release]; } response.routeStatuses = routeStatuses; [routeStatuses release]; JT_BLOCKTHREAD_MAIN callback(response); JT_POP_NETWORK(); JT_BLOCKTHREAD_END JT_BLOCKTHREAD_END }

    Read the article

  • Passing a NSArray between classes

    - by Althane
    So, my second question based off of this application I'm teaching myself Objective C with. I have a Data Source class, which for now looks mostly like: - (id) init { if (self = [super init]){ listNames = [[NSArray alloc] initWithObjects: @"Grocery", @"Wedding", @"History class",@"CS Class",@"Robotics",@"Nuclear Sciences", @"Video",@"Library",@"Funeral", nil]; NSLog(@"%@",listNames); } return self; } The .h looks as follows: @interface MainViewDataSource : NSObject { NSArray *listNames; } @property (nonatomic, retain) NSArray *listNames; -(NSArray *)getListNames; So that's where I make it. Now the problem is that when I try to get the array listNames, it returns nothing. The following piece: NSArray* data = [listData listNames]; Is supposed to put the information in listNames in data, but... isn't. Since I'm rather used to JAva, I'm betting this is an Objective C quirk that I don't know how to fix. Which is why I'd be here asking for help. What's the proper way to pass around NSArrays like this?

    Read the article

  • Setting an NSMutableArray in AppDelegate to be an NSMutableArray in

    - by aahrens
    What i'm trying to accomplish is to have an NSMutableArray defined in the AppDelegate. I then have two UIViewControllers. One view is responsible for displaying the array from the AppDelegate. The other view is used to add items to the array. So the array starts out to be empty. View1 doesn't display anything because the array is empty. The User goes to View2 and adds an item to the array in AppDelegate. Then when the user goes back to View1 it now displays one item. Here is how I'm trying to accomplish this @interface CalcAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UITabBarController *tabBarController; NSMutableArray *globalClasses; } @property (nonatomic,retain) NSMutableArray *globalClasses; My other view In the viewDidload I set the array in my View to be the one in the AppDelegate. In an effort to retain values. allCourses = [[NSMutableArray alloc]init]; CalcAppDelegate *appDelegate = (CalcAppDelegate *)[[UIApplication sharedApplication] delegate]; allCourses = appDelegate.globalClasses; Then I would update my allCourses array by adding a new item. Then try to set the array in the AppDelegate to be equal to the modified one. CalcAppDelegate *appDel = (CalcAppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(@"Size before reset %d",[appDel.globalClasses count]); appDel.globalClasses = allCourses; NSLog(@"Size after reset %d",[appDel.globalClasses count]); What I'm seeing that's returned is 2 in the before, and 2 after. So it doesn't appear to be getting updated properly. Any suggestions?

    Read the article

  • json-framework: EXC_BAD_ACCESS on stringWithObject

    - by Vegar
    UPDATE: I found that the reason for the previous error was an error in the documentation. The method should be named proxyForJson, not jsonProxyObject... But I'm still stuck, though. I now get an EXC_BAD_ACCESS error inside stringWithObject some where. Any clues? UPDATE 2: My proxyForJson implementation is a cut-n-paste from then documentation: - (id)proxyForJson { return [NSDictionary dictionaryWithObjectsAndKeys: Navn, @"Navn", Adresse, @"Adresse", Alder, @"Alder", nil]; } Trying to make json serialization work for my custom objective-c class. As I understand the documentation, json-framework can serialize custom objects, if they implement the jsonProxyObject method. So I have this class: @interface MyObject : NSObject { NSString *Name; NSString *Addresse; NSInteger Age; } @property (nonatomic, retain) NSString *Name; @property (nonatomic, retain) NSString *Addresse; @property (nonatomic, assign) NSInteger Age; - (id)jsonProxyObject; @end And I try to serialize an array with some instances in it: [json stringWithObject:list error:&error]; But all I get is he following error: "JSON serialisation not supported for MyObject" I guess the jsonWriter can't find my jsonProxyObject method for some reason, buy why? Regards.

    Read the article

  • Debugging Key-Value-Observing overflow.

    - by Paperflyer
    I wrote an audio player. Recently I started refactored some of the communication flow to make it fully MVC-compliant. Now it crashes, which in itself is not surprising. However, it crashes after a few seconds inside the Cocoa key-value-observing routines with a HUGE stack trace of recursive calls to NSKeyValueNotifyObserver. Obviously, it is recursively observing a value and thus overflowing the NSArray that holds pending notifications. According to the stack trace, the program loops from observeValueForKeyPath to setMyValue and back. Here is the according code: - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqual:@"myValue"] && object == myModel && [self myValue] != [myModel myValue]) { [self setMyValue:[myModel myValue]; } } and - (void)setMyValue:(float)value { myValue = value; [myModel setMyValue:value]; } myModel changes myValue every 0.05 seconds and if I log the calls to these two functions, they get called only every 0.05 seconds just as they should be, so this is working properly. The stack trace looks like this: -[MyDocument observeValueForKeyPath:ofObject:change:context:] NSKeyValueNotifyObserver NSKeyValueDidChange -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:] -[MyDocument setMyValue:] _NSSetFloatValueAndNotify …repeated some ~8k times until crash Do you have any idea why I could still be spamming the KVO queue?

    Read the article

  • Why do properties require explicit typing during compilation?

    - by ctpenrose
    Compilation using property syntax requires the type of the receiver to be known at compile time. I may not understand something, but this seems like a broken or incomplete compiler implementation considering that Objective-C is a dynamic language. The property "comment" is defined with: @property (nonatomic, retain) NSString *comment; and synthesized with: @synthesize comment; "document" is an instance of one of several classes which conform to: @protocol DocumentComment <NSObject> @property (nonatomic, retain) NSString *comment; @end and is simply declared as: id document; When using the following property syntax: stringObject = document.comment; the following error is generated by gcc: error: request for member 'comment' in something not a structure or union However, the following equivalent receiver-method syntax, compiles without warning or error and works fine, as expected, at run-time: stringObject = [document comment]; I don't understand why properties require the type of the receiver to be known at compile time. Is there something I am missing? I simply use the latter syntax to avoid the error in situations where the receiving object has a dynamic type. Properties seem half-baked.

    Read the article

  • How to write text(using CGContextShowTextAtPoint) dynamically near graph x and y-axis intervals?

    - by Rajendra Bhole
    I developed graph using NSObject class and using CGContext method. The following code displaying dynamically in X and Y-axis intervals, CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextSetLineWidth(ctx, 2.0); CGContextMoveToPoint(ctx, 30.0, 200.0); CGContextAddLineToPoint(ctx, 30.0, 440.0); for(float y = 400.0; y >= 200.0; y-=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, 28, y); CGContextAddLineToPoint(ctx, 32, y); CGContextStrokePath(ctx); //CGContextClosePath(ctx); } CGContextMoveToPoint(ctx, 10, 420.0); CGContextAddLineToPoint(ctx, 320, 420.0); //CGContextAddLineToPoint(ctx, 320.0, 420.0); //CGContextStrokePath(ctx); for(float x = 60.0; x <= 260.0; x+=30) { CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextMoveToPoint(ctx, x, 418.0); CGContextAddLineToPoint(ctx, x, 422.0); CGContextStrokePath(ctx); CGContextClosePath(ctx); } I want to write the dynamic text on the X and Y-axis lines near the intervals (like X-axis is denoting number of days per week and Y-axis denoting something per someting)? Thanks.

    Read the article

  • How to show AdMob ads in real iPhone device?

    - by iPhoney
    I want to integrate AdMob ads in my iPhone app. I'm using IB way to add the view and follow AdMob's pdf guide: 1. Add AdMob group(AdMobView.h,AdMobDelegateProtocol.h,libAdMob.a) 2. Add required frameworks(AudioToolbox,MediaPlayer,MessageUI,QuartzCore) 3. Add TouchJSON group 4. Add IBSupport group(AdViewController.h,AdViewController.m) 5. Add a 320*48 UIView in IB, add NSObject and change its class to AdViewController, link AdViewController's view to the 320*48 UIView and link AdViewController's viewController to current view controller. Now the iPhone simulator can show ads from AdMob, but when I test it on real device, I get the error "AdMob: Did fail to receive ad". I've tried to add test device's UDID to testDevices array, but still get the same error. - (NSArray *)testDevices { return [NSArray arrayWithObjects: ADMOB_SIMULATOR_ID, DEVICE_UDID, nil]; } Is there any problem in the above steps? Does anybody know why can't I get the ads in real device? By the way, what should be changed to build for real for-sale app, not just for test?

    Read the article

  • Adding an observer to UIImageView? observer & notifications

    - by sagar
    Each class has almost one method named addObserver [imgVURL addObserver:<#(NSObject *)observer#> forKeyPath:<#(NSString *)keyPath#> options:<#(NSKeyValueObservingOptions)options#> context:<#(void *)context#>] Here, imgVURL is an image which is going to be load an image asynchronously. When image will be loaded dynamically - other class will set an image from loaded data. Now, my question is how can we add an observer to UIImageView's instance. Observer and notifications are same or not ? If it is not then what's different ? Let's have some sample code That I did in my project to understand my question. // locating image view from Scroll view by it's tag imgVURL=(UIImageView*)[scrMain viewWithTag:(kTagImagesTag+i)]; // ImageViewURL is a class which contains methods of // didReceiveResponse // didReceiveData // connection ImageViewURL *tmp=[[ImageViewURL alloc] init]; // it has a nonatomic property which will take the reference of my image view tmp.imgV=imgVURL; // now I will pass a url from my an array to property strURL // in strUrl I have custom setter // in which I am initializing a connection tmp.strUrl=[NSURL URLWithString:[[tblmain objectAtIndex:i] valueForKey:@"url"]]; // from ImageViewURL.m file -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // NSLog@"ImageView Ref From - %@",imgV); // see imgV has reference of my -> imgVURL (nonatomic,assign) imgV.image=[UIImage imageWithData:myWebData]; [connection release]; connection=nil; } // as you can see in above code many many images are loaded asynchronously // now How can I add an observer to an imageview whether it received or not.

    Read the article

  • How to specify selector when CAKeyframeAnimation is finished?

    - by darenchow
    I'm using a CAKeyframeAnimation to animate a view along a CGPath. When the animation is done, I'd like to be able to call some other method to perform another action. Is there a good way to do this? I've looked at using UIView's setAnimationDidStopSelector:, however from the docs this looks like it only applies when used within a UIView animation block (beginAnimations and commitAnimations). I also gave it a try just in case, but it doesn't seem to work. Here's some sample code (this is within a custom UIView sub-class method): // These have no effect since they're not in a UIView Animation Block [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; // Set up path movement CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"path"]; pathAnimation.calculationMode = kCAAnimationPaced; pathAnimation.fillMode = kCAFillModeForwards; pathAnimation.removedOnCompletion = NO; pathAnimation.duration = 1.0f; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, self.center.x, self.center.y); // add all points to the path for (NSValue* value in myPoints) { CGPoint nextPoint = [value CGPointValue]; CGPathAddLineToPoint(path, NULL, nextPoint.x, nextPoint.y); } pathAnimation.path = path; CGPathRelease(path); [self.layer addAnimation:pathAnimation forKey:@"pathAnimation"]; A workaround I was considering that should work, but doesn't seem like the best way, is to use NSObject's performSelector:withObject:afterDelay:. As long as I set the delay equal to the duration of the animation, then it should be fine. Is there a better way? Thanks!

    Read the article

  • how to extend a protocol for a delegate in objective C, then subclass an object to require a conform

    - by fess .
    I want to subclass UITextView, and send a new message to the delegate. So, I want to extend the delegate protocol, What's the correct way to do this? I started out with this: interface: #import <Foundation/Foundation.h> @class MySubClass; @protocol MySubClassDelegate <UITextViewDelegate> - (void) MySubClassMessage: (MySubClass *) subclass; @end @interface MySubClass : UITextView { } @end implementation: #import "MySubClass.h" @implementation MySubClass - (void) SomeMethod; { if ([self.delegate respondsToSelector: @selector (MySubClassMessage:)]) { [self.delegate MySubClassMessage: self]; } } @end however with that I get the warning: '-MySubClassMessage:' not found in protocol(s). I had one way working where I created my own ivar to store the delegate, then also stored the delegate using [super setDelegate] but that seemed wrong. perhaps it's not. I know I can just pass id's around and get by, but My goal is to make sure that the compiler checks that any delegate supplied to MySubClass conforms to MySubClassDelegate protocol. To further clairfy: @interface MySubClassTester : NSObject { } @implementation MySubClassTester - (void) one { MySubClass *subclass = [[MySubClass alloc] init]; subclass.delegate = self; } @end will produce the warning: class 'MySubClassTester' does not implement the 'UITextViewDelegate' protocol I want it to produce the warning about not implementing 'MySubClassDelegate' protocol instead. Thanks, a bunch. (thanks brad)

    Read the article

  • Navigation view system with webview problem with touches!

    - by Gonçalo Falcão
    Hello i have search everything and i didn't figure this out! I have a tab bar controller with 5 navigation controlls, in one of the navigation control, i have a view, with a table view inside, and when i click that item i push a new view, that view have view -webview -view i create that second view(is transperant) because i need to handle a single tap to hide my toolbar and navigation bar, and the webview was eating all the touches! I put that view and implement on the view controller -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch* touch = [touches anyObject]; if(touch.tapCount == 2){ [NSObject cancelPreviousPerformRequestsWithTarget:self]; } [[wv.subviews objectAtIndex:0] touchesBegan:touches withEvent:event]; [super touchesBegan:touches withEvent:event]; } -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ [[wv.subviews objectAtIndex:0] touchesMoved:touches withEvent:event]; [super touchesMoved:touches withEvent:event]; } -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch* touch = [touches anyObject]; if(touch.tapCount == 1){ [self performSelector:@selector(hideBars) withObject:nil afterDelay:0.3]; } [[wv.subviews objectAtIndex:0] touchesEnded:touches withEvent:event]; [super touchesEnded:touches withEvent:event]; } -(void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ [[wv.subviews objectAtIndex:0] touchesCancelled:touches withEvent:event]; [super touchesCancelled:touches withEvent:event]; } wv is my UIWebView IBOutlet now i can get the the touches in my controller and send them to my webview. So i thought everything was working, i'm able to scroll, but now when i have links i'm not able to click them. And the webview is detecting the links i have made that test. So any other way to implements this to get the touches in the links, or i should change this workaround to hide the toolbars so i can have the full functionability of the webview? Thks for the help in advance.

    Read the article

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