Best ios questions in September 2011

Feed dialog generating errors with iOS SDK

17 votes

UPDATE: This problem was resolved when facebook fixed their service.

I'm trying to get the feed dialog to work for sharing with facebook. I had it all working before with the old, deprecated API and SDK, but have just moved to using the current iPhone SDK and am trying an example directly from the documenation here;

I keep getting the error, "Error with publishing" "There was a problem generating the Feed story from the provided data" and I cannot see what I'm doing wrong. Note that I have taken out the message parameter as it was deprecated in July, but I get the same problem whether or not that parameter is present.

Facebook *facebook = [[Facebook alloc] initWithAppId:kFacebookAppId andDelegate:self];


NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               kFacebookAppId, @"app_id",
                               @"https://developers.facebook.com/docs/reference/dialogs/", @"link",
                               @"http://fbrell.com/f8.jpg", @"picture",
                               @"Facebook Dialogs", @"name",
                               @"Reference Documentation", @"caption",
                               @"Using Dialogs to interact with users.", @"description",
                               nil];   

[facebook dialog:@"feed" andParams:params andDelegate:self];

Can anyone see what I might be doing wrong? Thanks!

Here's the error screen

I don't think you are doing something wrong.

Just experienced the same problem with with my working app.

Most likely an issue on the side of facebook

Where are the standard looking iOS controls\styles in Delphi XE2?

12 votes

We are currently in the process of evaluating Delphi XE2, and as you would expect I've started with FireMonkey as OS X and iOS development is of great interest. I've seen a couple of walkthrough's where people have created iOS apps using XE2 and I've managed to do the same, however the bread and butter of 'business applications' on an iPhone (which is how iOS support is being marketed) are buttons, lists, grids and connectivity (REST?).

Anyway, once you've created your iOS HD project the TButton initially looks green, whereas the TSpeedButton and TToolbar looks exactly like it should (blue gradient). The TToolbar doesnt have any way of adding buttons, presumably this is just a Panel, then?

Has anyone created styles for FM iOS HD apps, or do any of the wrappers allow direct creation of the standard iPhone controls?

I apologise if that sounds a little backwards given that I am attempting to evaluate using the trial version (which among other things doesnt provide the source, for obvious reasons!).

Thanks,

Ross

FireMonkey does not have standard iOS or OS X components. It draws all the components on its own, using a complicated set of layered sub-components, which are all editable with the FMX style editor in the IDE (or with a text editor outside the IDE).

So you can mimic the iOS or OS X components with the styles you get with the product or with your own custom styles. But to use the original UIKit/Cocoa Touch components, you'll have to use the FreePascal translations and conversions of the original Apple headers, and not FMX.

There is no designer for such UIs, unless you want to use Xcode 4.x. I don't know if FreePascal can load and use .xib files, though (although, why not? Probably just not automatically). You can, of course, create and place such components in code, at runtime.

So you either:

  • use FMX and design your own styles or modify the existing styles to your need, or
  • use Xcode and .xib files. Not sure how to do that with FreePascal.

FWIW, you can place any FMX component on any other FMX component (e.g. also a textbox on a button on an arcdial on a list item in a listbox), so it should be possible to place buttons on a toolbar. You probably have to take care of their alignment and arrangement, though, and probably also for their behaviour. Use a TLayout, Padding, Margins and alignment for that.

10 votes

I'm a beginner with GCD and CoreData, and I need your help to use CoreData with CGD, so that the UI is not locked while I add 40.000 records to CoreData.

I know that CD is not thread-safe, so I have to use another context, and then save the data and merge contexts, as far as I was able to understand from some articles.

What I could'n do yet, is put the pieces together.

So, in my code, I need your help on how to to that.

I have:

    {

    /*some other code*/

    for (NSDictionary *memberData in arrayWithResult){

    //get the Activities for this member
    NSArray *arrayWithMemberActivities = [activitiesDict objectForKey:[memberData objectForKey:@"MemberID"]];

    //create the Member, with the NSSet of Activities
    [Members createMemberWithDataFromServer:memberData
                         andActivitiesArray:arrayWithMemberActivities
                              andStaffArray:nil
                           andContactsArray:nil
                     inManagedObjectContext:self.managedObjectContext];
}

How can I transform this to work on the background, and then, when done saving, save the data and update the UI, without block the UI while is saving the 40.000 objects?

Thanks,

RL

Here's a good framework for you to try. Feel free to come back if you have any questions:

dispatch_queue_t request_queue = dispatch_queue_create("com.yourapp.DescriptionOfMethod", NULL);
dispatch_async(request_queue, ^{

    // Create a new managed object context
    // Set its persistent store coordinator
    AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *newMoc = [[NSManagedObjectContext alloc] init];
    [newMoc setPersistentStoreCoordinator:[theDelegate persistentStoreCoordinator]];

    // Register for context save changes notification
    NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
    [notify addObserver:self 
               selector:@selector(mergeChanges:) 
                   name:NSManagedObjectContextDidSaveNotification 
                 object:newMoc];

    // Do the work
    // Your method here
    // Call save on context (this will send a save notification and call the method below)
    BOOL success = [newMoc save:&error];
    [newMoc release];
});
dispatch_release(request_queue);

And in response to the context save notification:

- (void)mergeChanges:(NSNotification*)notification 
{
    AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
    [[theDelegate managedObjectContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
}

And don't forget to remove the observer from the notification center once you are done with the background thread context.

[[NSNotificationCenter defaultCenter] removeObserver:self];

How to access iOS accelerometer in Delphi XE2?

8 votes

How do I access the accelerometer in iOS using Delphi XE2?

I tried looking through the IDE but did not find a component.

Delphi XE2 supports deploying to OSX on a mac. Deploying to an iPhone is apparently pretty easy, but it still involves using XCode as a final deployment tool. Since Delphi doesn't "officially" support deploying to iPhone hardware, I doubt they have included any components that are specific to it.

Disclaimer: I just downloaded XE2 a few hours ago, and I've only deployed one mac application so far (and it worked beautifully). So I'm far from an expert.

How to log all methods used in iOS app

7 votes

I'm taking over the development of an iPad app for a client. There's a substantial amount of work that's already been done and I'm trying to piece together how the whole thing is designed to run.

One of the things I'd like to do is log which methods get called when the app runs. I've seen a custom DTrace script that's meant to log all methods from startup, but when I run it in Instruments I get no results.

What's the best way of logging the methods?

Inspired by tc's answer to a similar question here, I put together a debug breakpoint action that will log out the class and method name for every time objc_msgSend() is triggered in your application. This works similarly to the DTrace script I described in this answer.

To enable this breakpoint action, create a new symbolic breakpoint (in Xcode 4, go to the breakpoint navigator and create a new symbolic breakpoint using the plus at the bottom left of the window). Have the symbol be objc_msgSend, set it to automatically continue after evaluating actions, and set the action to be a debugger command using the following:

printf "[%s %s]\n", (char *)object_getClassName(*(long*)($esp+4)),*(long *)($esp+8)

Your breakpoint should look something like the following:

Breakpoint action

This should log out messages like this when run against your application:

[UIApplication sharedApplication]
[UIApplication _isClassic]
[NSCFString getCString:maxLength:encoding:]
[UIApplication class]
[SLSMoleculeAppDelegate isSubclassOfClass:]
[SLSMoleculeAppDelegate initialize]

If you're wondering where I pulled the memory addresses, read this Phrack article on the Objective-C runtime internals. Unfortunately, I think these memory addresses will only work against the Simulator, so you might need to tweak this to run against applications on the iOS devices.

Also, I think you'll see that logging out every method called in your application will overwhelm you with information. You might be able to use some conditions to filter this, but I don't know if this will help you to learn how your code executes.

iOS: How to avoid autoreleased copies when manipulating large NSString instance?

7 votes

I have a scenario in an iOS application where manipulating a very large NSString instance (an HTTP response, upwards of 11MB) results in multiple large intermediaries being in memory at once, since the SDK methods I am calling return new autoreleased instances. What is the best approach to take here?

For example, assuming that largeString is an autoreleased NSString instance:

NSArray *partsOfLargeString = [largeString componentsSeparatedByString:separator];

for (NSString *part in partsOfLargeString) {
    NSString *trimmedPart = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSData *data = [trimmedPart dataUsingEncoding:NSUTF8StringEncoding];
}

It would be great if there were non-autoreleased equivalents to componentsSeparatedByString or stringByTrimmingCharactersInSet, but I'm not looking to implement these myself.

To my knowledge, there isn't a way to "force" release an object that has already been added to an autorelease pool. I know that I can create and use my own autorelease pool here, but I'd like to be extremely granular and having autorelease pools around individual statements definitely isn't a very scalable approach.

Any suggestions are much appreciated.

As Bill said, I’d first try to have an autorelease pool for each loop iteration, e.g.:

for (NSString *part in partsOfLargeString) {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSString *trimmedPart = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSData *data = [trimmedPart dataUsingEncoding:NSUTF8StringEncoding];
    …

    [pool drain];
}

or, if you’re using a recent enough compiler:

for (NSString *part in partsOfLargeString) {
    @autoreleasepool {
        NSString *trimmedPart = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSData *data = [trimmedPart dataUsingEncoding:NSUTF8StringEncoding];
        …
    }
}

If that’s still not acceptable and you do need to release objects in a more granular fashion, you could use something like:

static inline __attribute__((ns_returns_retained))
id BICreateDrainedPoolObject(id (^expression)(void)) {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    id object = expression();
    [object retain];
    [pool drain];
    return object;
}

#define BIOBJ(expression) BICreateDrainedPoolObject(^{return (expression);})

which evaluates the expression, retains its result, releases any ancillary autoreleased objects and returns the result; and then:

for (NSString *part in partsOfLargeString) {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSString *trimmedPart = BIOBJ([part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]);
    NSData *data = BIOBJ([trimmedPart dataUsingEncoding:NSUTF8StringEncoding]);
    [trimmedPart release];

    // do something with data
    [data release];

    …

    [pool drain];
}

Note that, since the function returns a retained object, you’re responsible for releasing it. You’ll have control over when to do that.

Feel free to choose better names for the function and macro. There might be some corner cases that should be handled but it should work for your particular example. Suggestions are welcome!

Using iOS 5 features without breaking backward compatibility

6 votes

My application is currently compiled against the latest iOS 4.x SDK. Once iOS 5.0 SDK is out, would it be possible for me to use the new iOS 5.0 SDK features in my application and yet have it run on iOS 4 devices (but with the parts using the new features disabled)?

To answer the question generally, the Objective-C runtime is fully reflective, which means that you can query which methods an object supports (via respondsToSelector:) and get hold of classes by name at runtime (via NSClassFromString). iOS binaries also support the concept of weak linkage with frameworks, which means that the framework will be loaded if it is available but that you don't consider it a fatal error if the framework isn't available (as is the default behaviour).

That means that when Apple release new versions of the OS you can write code that uses new features on the latest version of the OS but functions fine without them if those new features are new bits of API.

Apple also sometimes supply new SDK features that aren't new APIs, such as when the Clang static analyser was added to Xcode. As those features usually don't require any runtime support they're fully usable. iOS 5 is a little unique because Apple's commits to the LLVM project suggest that there are some new compile time features in amongst the ARC stuff that rely on some runtime support. So they'll be unavailable, if indeed they're in the tools as Apple intend to distribute them.

Detect if time format is in 12hr or 24hr format

6 votes

Is there any way to detect if the current device of the app uses 12h our 24h format, so that I can use one NSDateFormatter for 12h and one for 24h depending on the users language/loaction setting? Just Like the UIDatePicker detects and shows the AM/PM picker if it is 12h format.

I figured it out, its pretty easy. I just added this code to viewDidLoad :

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
[formatter release];
NSLog(@"%@\n",(is24h ? @"YES" : @"NO"));

And it perfectly returns YES or NO depending on the locale.

Develop an iOS App for Cydia

6 votes

How can I start developing simple iOS tweaks for Cydia?

What's the difference in compiling an app for the official App Store and Cydia?

Developing a tweak is quite different from developing a self contained app. If you want to do it all yourself, read up on Objective C runtime programming. However, this is not how the vast majority of tweak developers do it, as there are several easier options.

If you have experience with Objective C (enough to be able to develop an app), there isn't a whole lot more you need to know to make a tweak. Dustin Howett, a developer who has made several tweaks for Cydia, made a tool called theos which vastly simplifies the process. You can read up on it here. There is also a very active IRC channel at irc.saurik.com #theos. Finally, you may want to check out the github pages of some popular tweak developers that use theos, so you can better understand the syntax (chpwn, DHowett, rpetrich).

Those three methods are how I learned to write tweaks, and once you understand theos it is really quite simple. theos also has systems for creating self contained apps as well as other plugins, so download it and see what is best for what you want. A quick google search will also turn up several useful theos tutorials (1, 2). Good luck!

One final thing to note is that you may want to hold off on developing for a couple weeks, the reason being that Apple may be releasing iOS 5 soon and things could change, as well as the fact that everyone on the #theos IRC will refuse to help with problems pertaining to iOS 5.

How to Start Three20 Photo Viewer in Thumbnail view?

6 votes

I followed How To Use the Three20 Photo Viewer by Ray Wenderlich tutorial it was very clear and working perfectly, my question as the title, How to Start Three20 Photo Viewer in Thumbnail view?

I am greatly appreciative of any guidance or help.

You should use TTThumbsViewController instead of TTPhotoViewController. There's a good example of it in three20 TTCategory sample app.

TTThumbsViewController also uses a photo source, so you won't have to change that much code. Your Photo viewer should extend TTThumbsViewController and implement the TTThumbsViewControllerDelegate delegate functions.

You can load the photo source in your viewDidLoad function:

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
  NSMutableArray* photos = [NSMutableArray array];
  for (int i=kImagesCount;i>=1;i--) {
    Photo* photo = [[[Photo alloc] initWithURL:[NSString stringWithFormat:@"bundle://%d.png", i]
                                      smallURL:[NSString stringWithFormat:@"bundle://%dt.png", i]
                                          size:CGSizeMake(400, 400)] autorelease];
    [photos addObject:photo];
  }

  self.photoSource = [[PhotoSource alloc]
                      initWithType:PhotoSourceNormal
                      title:@"Select Picture"
                      photos:photos 
                      photos2:nil];

}

How to tell if object is in an NSAutoreleasePool

6 votes

I would like to know how many times an object has been autoreleased. I've used objective c long enough that it's generally straight forward to know whether an object has been autoreleased or not, however I constantly see questions dealing with memory and retain counts. At some point an answer always ends, "You can't trust the retainCount of an object" - which I agree with, BUT if you could determine how many times an object has been autoreleased, then you actually could trust the retainCount if you added a category like:

@interface NSObject (NSObject_MemoryDebugging)
- (NSUInteger) autoReleaseCount;
- (NSUInteger) retainCountWithAutoRelease;
@end

@implementation]
/** Determine how many times this object has been marked for autorelease **/
- (NSUInteger) autoReleaseCount;
{
   // ??? not sure how to figure this out.
   return 0;
}

 - (NSUInteger) retainCountWithAutoRelease
{
   NSUInteger retainCount = [self retainCount];
   NSUInteger autoReleaseCount = [self getAutoReleaseCount];  // ???
   return retainCount - autoReleaseCount;
}
@end

There would still be an exception for immutable types as those typically increase the retain count during a copy, so you still can't trust retainCount on those.

What I am NOT proposing

I am not seeking this answer to use retainCount in production code. However, I can see this as being valuable for someone debugging memory issues.

I imagine some people will HATE this question since programmers should not care about how many times an object has been autoreleased. Coding should be all about balancing allocs, retain, copy, new with release, end of story. However, the point of this is to help out people banging their heads. [NSObject retainCount] burns a lot of people, and an answer to this question would be pretty cool.

I'm certain there's a way to determine how many times an object has been autoreleased. I just don't know what it is, hence the question.

See similar question: Objects inside NSAutoreleasePool in objective-c.

Edit


Thank you everyone for your answers. You may find this interesting => Ariel pointed out that GNUStep's implementation of Cocoa and specifically it's NSAutoReleasePool has this method: +(NSUInteger)autoreleaseCountForObject:(id)anObject. This method is slow, and only returns the autorelease count from NSAutoReleasePools on the callers thread. Still... It's interesting that its there. The docs cite that it is really only useful for debugging. This is really what I was hoping to find (or find possible) in the Cocoa framework somehow.

I agree with the answers given that even if it were possible to get the autorelease count that better tools exist (Zombies, Leaks, static analyzer).

First, you'd have to deal with multiple autorelease pools and an object being autoreleased more than once, possibly in multiple pools.

Second, it's not (just) NSAutoreleasePool that's making -retainCount untrustworthy. The problem is that all sorts of objects, both yours and Apple's, retain things for all sorts of reasons, most unbeknownst to you. Even accounting for autorelease, your objects will often not have the retain count you expect, because behind the scenes, something's observing it or placing it in a dictionary temporarily, etc.

The best ways to debug memory issues are the Leaks instrument, NSZombie, and the static analyzer.

Is there a simple way (in Cocoa/iOS) to queue a method call to run once in the next run loop?

6 votes

UIView has a setNeedsDisplay method that one can call several times within the same event loop, safe in the knowledge that the redrawing work will happen soon, and only the once.

Is there a generic mechanism for this sort of behaviour Cocoa? A way of of saying, "Queue a selector as many times as you like, when it's time, the selector will run once & clear the queue."

I know I could do this with some kind of state tracking in my target, or with an NSOperationQueue. I'm just wondering if there's a lightweight approach I've missed.

(Of course, the answer may be, "No".)

setNeedsDisplay is not a good example of what you're describing, since it actually does run every time you call it. It just sets a flag. But the question is good.

One solution is to use NSNotificationQueue with NSNotificationCoalescingOnName.

Another solution is to build a trampoline to do the coalescing yourself. I don't have a really good blog reference for trampolines, but here's an example of one (LSTrampoline). It's not that hard to build this if you want to coalesce the messages over a period of time. I once built a trampoline with a forwardInvocation: similar to this:

- (void)forwardInvocation:(NSInvocation *)invocation {
  [invocation setTarget:self.target];
  [invocation retainArguments];
  [self.timer invalidate];
  self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeout invocation:invocation repeats:NO];
}

This actually coalesces all messages to the object over the time period (not just matching messages). That's all I needed for the particular problem. But you could expand on this to keep track of which selectors are being coalesced, and check your invocations to see if they match "sufficiently."

To get this to run on the next event loop, just set timeout to 0.

I keep meaning to blog about trampolines. Required shilling: My upcoming book covers trampolines in Chapter 4 and Chapter 20.

Is divide slower than Multiply?

5 votes

Ok, this might sound like a strange question but it is an interesting one. I am coding for iOS and have been told that it is always best to multiply rather than divide values as it is faster.

I know that processors these days probably make this a non issue but my curiosity has gotten the better of me and I am wondering if anyone might be able to shed some light on this for me.

SO..... My question is this -
is:

player.position = ccp(player.contentSize.width / 2, winSize.height / 2);

slower than:

player.position = ccp(player.contentSize.width * 0.5, winSize.height * 0.5);

On most processors division is slower than multiplication for the same data types. In your example your multiplication is a floating point operation, if width and height are integer types, the result may be very different and may depend on both your processor and your compiler.

However most compilers (certainly GCC) will translate a division by a constant power-of-two as in your example, to a right-shift where that would be more efficient. That would generally be faster than either a multiply or divide.

What's fastest way to re-test iPhone core data migration to a new version?

5 votes

What's fastest way to re-test iPhone core data migration to a new version?

That is, how would one set up an easy/quick way to:

  • set up older version of app on simulator
  • run the new version of the app from Xcode which will as part of running it on the simulator effectively run the migration

BACKGROUND- haven't had to do a migration yet. It's not to me in Xcode how to do the first bullet in particular. Would one use a previous image/snapshot as part of the approach?

What I always did is:

  1. navigate to your applications folder /Users/username/Library/Application Support/iPhone Simulator/4.3.2/ notice the iOS version number, its the one you're using in the simulator
  2. there should be one or more folders with hash values, found the one you're working with
  3. in the documents folder should be your .sqlite database file (as long as you haven't changed the directory in code)
  4. backup that one (for example version 1)
  5. when you want to test the migration, simply replace this db file with your backup

(the hash may change when you delete and rebuild your app)

Why do Objective-c protocols adopt other protocols?

5 votes

I've seen Objective-c protocols defined in the following way:

@protocol MyProtocol <SomeOtherProtocol>
// ...
@end

Why do protocols adopt other protocols? I'm especially curious why a protocol would adopt the NSObject protocol.

It is simply the same concept as inheritance for classes. If a protocol adopt another protocol, it "inherits" the declared methods of this adopted protocol.

The NSObject protocol especially declares methods such as respondsToSelector:. So this is especially useful if you declare a @protocol that have @optional methods, because when you will then call methods on objects conforming this protocol, you will need to check if the object responds to the method before calling it if this method is optional.


@protocol SomeProtocol <NSObject>
-(void)requiredMethod;
@optional
-(void)optionalMethod;
@end

@interface SomeObject : NSObject
-(void)testMyDelegate;
@property(nonatomic, assign) id<SomeProtocol> myDelegate;
@end

@implementation SomeObject
@synthesize myDelegate

-(void)testMyDelegate {
    // Here you can call requiredMethod without any checking because it is a required (non-optional) method
    [self.myDelegate requiredMethod];

    // But as "optionalMethod" is @optional, you have to check if myDelegate implements this method before calling it!
    if ([myDelegate respondsToSelector:@selector(optionalMethod)]) {
        // And only call it if it is implemented by the receiver
        [myDelegate optionalMethod];
    }
}
@end

You will only be able to call respondsToSelector on myDelegate if myDelegate is declared as a type that implements respondsToSelector (otherwise you will have some warnings). That's why the <SomeProtocol> protocol needs to adopt itself the <NSObject> protocol, which itself declares this method.

You may think of id<SomeProtocol> as "any object, whatever its type (id), it just has to implement the methods declared in SomeProtocol, including the methods declared in the parent protocol NSObject. So it can be an object of any type but because SomeProtocol adopts the NSObject protocol itself, it is guaranteed that you are allowed to call respondsToSelector on this object, allowing you to check if the object implements a given method before calling it if it is optional.


Note that you may also not make SomeProtocol adopt the NSObject protocol and instead declare your variable as id<SomeProtocol,NSObject> myDelegate so that you can still call respondsToSelector:. But if you do that you will need to declare all your variables this way everywhere you use this protocol... So this is much more logical to make SomeProtocol directly adopt the NSObject protocol ;)

annotation on current location

5 votes

I'm working on the project in which i added a button on pressing it should take me to my current location on map and should show the blue indicator to indicate the location,here is the code:

-(IBAction)gotoLocation
{
if(curntloc)
 {
    MKCoordinateRegion mapRegion;   
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.0112872;
    mapRegion.span.longitudeDelta = 0.0112872;
    [self.mapView setRegion:mapRegion animated: YES];
 }
else
  { 
    curntloc = [[CLLocation alloc] initWithLatitude:21.192415 longitude:72.821159];
    MKCoordinateRegion mapRegion;
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.0112872;
    mapRegion.span.longitudeDelta = 0.0112872;
    [self.mapView setRegion:mapRegion animated: YES];
  }
}

This works fine on simulator you can see it in image,

on top is the button on pressing which i get the location statically passed on second loop but on iPhone it won't works

but when i try to test it on iPhone it's getting crashed.what may be the possible reasons can any one point out? thanks

First of all i want to tell you that from simulator you can't get current location. in your code you just used a static lat. long. and for the device i share a link just check.

http://pastebin.com/Vv1wvyBh

which may be helpful to you :)

Thanks.

object rotation is not proper - iPhone application

5 votes

I am facing a typical problem in rotating an object. Description is as given below
I have taken two CGPoint let say point1 and point2
point1 = (50,50)
point2 = (150, 50)
this point will draw a horizontal line.

Now i am drawing a rectangle with that point on it. Width is 100 and height is 10. Angle is 0.
see screen shot
enter image description here

works fine
now i change the point let say
point1 = (50,50)
point2 = (50,150)
this point will draw a vertical line.

For rectangle Angle is 90.
With this point rectangle is not drawing properly
see screen shot
enter image description here

My code for drawing rectangle is :

    CGPoint mid = CGPointMake((point1.x+point2.x)/2, (point1.y+point2.y)/2)
    CGPoint UL = CGPointMake(mid.x + ( Width / 2 ) * cos (A) - ( Height / 2 ) * sin (A) ,  mid.y + ( Height / 2 ) * cos (A)  + ( Width / 2 ) * sin (A));
    CGContextMoveToPoint(context, UL.x,routeView.frame.size.height - UL.y);
    CGPoint UR = CGPointMake(mid.x - ( Width / 2 ) * cos (A) - ( Height / 2 ) * sin (A) ,  mid.y + ( Height / 2 ) * cos (A)  - ( Width / 2 ) * sin (A));
    CGContextAddLineToPoint(context, UR.x,routeView.frame.size.height - UR.y);
    CGPoint BR = CGPointMake(mid.x - ( Width / 2 ) * cos (A) + ( Height / 2 ) * sin (A) ,  mid.y - ( Height / 2 ) * cos (A)  - ( Width / 2 ) * sin (A));
    CGContextAddLineToPoint(context, BR.x,routeView.frame.size.height - BR.y);
    CGPoint BL = CGPointMake(mid.x + ( Width / 2 ) * cos (A) + ( Height / 2 ) * sin (A) ,  mid.y - ( Height / 2 ) * cos (A)  + ( Width / 2 ) * sin (A));
    CGContextAddLineToPoint(context, BL.x,routeView.frame.size.height - BL.y);
    CGContextAddLineToPoint(context, UL.x,routeView.frame.size.height - UL.y);

    CGContextStrokePath(context);

Here A is Angle and it is not static, mid is middle point of point1 and point2

for more ref see this

Am I missing something? Please help me if you have any idea.......

Thanks,

Let me guess, it's actually rotated about 26 degrees too far, right?

(90 x 180) / Pi ~= 5156.62 = (360 x 14) + 90 + 26.62

You rotated it 90 radians by mistake.