dimanche 28 juin 2015

Is there a perfect way to use iOS Framework template instead of static library now?

Since iOS8 and Xcode6 has release for a year, I have still cannot find a canonical tutorial for using Framwork template (iOS Universal Framework Mk 8) to develope a static library.

enter image description here

Even though the most popular Repo I think, kstenerud/iOS-Universal-Framework, has shut down when iOS8 Framework release.

enter image description here


However, when I try to develope a Static Framework I got ton of issues to resolve:

  1. I still have to do lipo for x86_64, i386, arm64, amrv7;
  2. remove Code signature from Framework;
  3. Build a resource bundle and import it to app project independent;
  4. Framework Info.plist and modules seem useless;
  5. Still a little worried if Apple will refuse my app since use a Static Framework.

Is there a good tutorial for building and using Static Framework? Any help will be appreciated! Thx.

I get error when I add a UITableView

I have a static UITableView, and in one of the cells, I have a dynamic UITableView. Here is the code I used:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;

    if (self.tableView == tableView) {
        cell = [tableView cellForRowAtIndexPath:indexPath];
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.textLabel setText:self.tagsArray [indexPath.row]];
    }
    return cell;
}

When I run the app, it crashes with the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106efbc65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106b94bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000106efbaca +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x00000001067a998f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   UIKit                               0x000000010762fa83 -[UITableView _configureCellForDisplay:forIndexPath:] + 128
    5   UIKit                               0x0000000107637a41 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 533
    6   UIKit                               0x0000000107616248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    7   UIKit                               0x000000010762c8a9 -[UITableView layoutSubviews] + 210
    8   UIKit                               0x00000001075b6a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    9   QuartzCore                          0x0000000106588ec2 -[CALayer layoutSublayers] + 146
    10  QuartzCore                          0x000000010657d6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    11  QuartzCore                          0x000000010657d546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    12  QuartzCore                          0x00000001064e9886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    13  QuartzCore                          0x00000001064eaa3a _ZN2CA11Transaction6commitEv + 462
    14  QuartzCore                          0x00000001064eb0eb _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    15  CoreFoundation                      0x0000000106e2eca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    16  CoreFoundation                      0x0000000106e2ec00 __CFRunLoopDoObservers + 368
    17  CoreFoundation                      0x0000000106e24a33 __CFRunLoopRun + 1123
    18  CoreFoundation                      0x0000000106e24366 CFRunLoopRunSpecific + 470
    19  GraphicsServices                    0x000000010ad61a3e GSEventRunModal + 161
    20  UIKit                               0x0000000107536900 UIApplicationMain + 1282
    21  myBudget                            0x000000010611fe5f main + 111
    22  libdyld.dylib                       0x0000000108952145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why do I get this error, and what can I do to fix it?

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

samedi 27 juin 2015

Changing the status bar color on UISearchController

I'm trying to change iOS 8 search bar status bar color but I tried the UIStatusBarStyleLightContent with no luck anyone knows a better way? Example of how it looks right now

Get the number of lines in UILabel iOS8

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a UILabel based of its set text?

I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

What is the point of a nil AutoreleasingUnsafeMutablePointer in a Swift closure?

I was reading the different ways to parse REST API calls in Swift and came across the following:

var url : String = "http://ift.tt/1tENtnZ"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

The one line that makes no sense to me is var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil. We already captured our NSError parameter and stored it in a variable called error, and now we're overwriting that and making it nil in our first line in the closure? Or if somehow Swift then performs a downcast of the error from type NSError! to AutoreleasingUnsafeMutablePointer<NSError?>, then can someone explain how that happens?

Thanks!

UITextInputCurrentInputModeDidChangeNotification return nill in ios 8.3

I want to detect current input mode of keyboard, and change text direction with respect to it (rtl if arabic, and ltr if english) in viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(changeInputMode:)
                                             name:UITextInputCurrentInputModeDidChangeNotification object:nil];

} and in changeInputMode:

-(void)changeInputMode:(NSNotification *)notification
{
    UITextInputMode *thisInputMode = [notification object];

    NSLog(@"inputMethod=%@",thisInputMode);
}

but thisInputMode is nill! if I use this code instead:

    NSString *inputMethod = [[UITextInputMode currentInputMode] primaryLanguage];
    NSLog(@"inputMethod=%@",inputMethod);

it works fine and detects current password, but currentInputMode is deprecated. why [notification object] returns nill?

Add lines on ImageView IOS (objective c)

enter image description here

I need some help to get this thing working..

Basically on button click, I have to add a line of fixed width with circle end points on the ImageView. User can add upto 5 lines. If I click on any circle (red dot) end point of line, it should allow to resize the line. Point can be dragged to any position on screen and line has to be straight. At the end, i should be able to calculate the length of each line. I just spent a lot of time on this and referring other similar answers. But so far, no luck.. Any reference code or links is greatly appreciated. Thanks!

IOS resize or reposition line on touching end points (Objective c)

I am trying to resize the line, by touching the red circle points. Let's say, I want to move this line above lips in the image below, How can i achieve this. The line is not moving from the position. I have just started up with this thing and can't find much relevant resources to accomplish this. Trying the best...Please guide me in the right direction. Below is my code and reference image.

Objective c code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];

    //Add second circle
    [path moveToPoint:CGPointMake(100.0, 100.0)];
    [path addLineToPoint:CGPointMake(200, 200)];
    [path moveToPoint:CGPointMake(200, 200)];

    [path addArcWithCenter:CGPointMake(200, 200) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];


    [path closePath];
    [[UIColor redColor] setStroke];
    [[UIColor redColor] setFill];
    [path stroke];
    [path fill];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 2.0;
    shapeLayer.fillColor = [[UIColor redColor] CGColor];

    [self.view.layer addSublayer:shapeLayer];

}

enter image description here

I will add multiple lines like this and my ultimate aim is to move individual line at any position in the image and get measurement of that area using line size.

EDIT: The scenario is, at any given time there will be some flexible lines available on the screen. Lets's say by clicking button, one more new line will be added to screen. The user can just drag any end point to resize the line in any direction. I can't get this thing working correctly.. no luck.

Here is my gist file link, http://ift.tt/1dp9Hm0 It basically adds a UIView to create a line on image. The code in gist allows me to resize the line height by moving touch points up and down but doesn't allow me to rotate the angle of line and adding text in the centre. THANKS

Thanks!

How to get all the classes of an application specified with identifier in iOS?

I want to get all the classes of a specified application (maybe any other apps, not only the app itself), I can get the NSBundle of that application with it's identifier, but how can I get the classes with the NSBundle, or can I get the classes directly with the application's identifier? We assume it could be a jailbroken environment.I tryied objc_copyClassNamesForImage but failed, does any one have ideas? Any help will be appreciated!

NSBundle * bundle = [NSBundle bundleWithIdentifier:appIdentifier];
NSString * bundlePath = [bundle bundlePath];
NSLog(@"%@", bundlePath);

unsigned int count;
const char **classes;

classes = objc_copyClassNamesForImage([bundlePath UTF8String], &count);

for (int i = 0; i< sizeof(classes)/sizeof(classes[0]); i++){
    NSLog(@"class name: %s", classes[i]);
}

Parse Relation [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I have a jobs app that enables users to view jobs. Jobs is a class in my Parse backend. I want to create a Favorites tab where user can mark certain jobs.

I've created a Relations Column in my User Class referring it to my Jobs class.

However, I have ran into this when the user taps to make the job a favorite: [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I feel like my PFRelation coding is spot on. I've researched this error but cannot seem to find any subject that relates to my problem. I must be making a mistake somewhere but

@interface JobDetailViewController ()

@end

@implementation JobDetailViewController

@synthesize jobPhoto;
@synthesize RotationLabel;
@synthesize QualificationsTextView;
@synthesize Job_DescriptionTextView;
@synthesize TypeLabel;
@synthesize LocationLabel;
@synthesize ClearanceLabel;
@synthesize PositionLabel;
@synthesize job;
@synthesize POC;
@synthesize Email;
@synthesize Phone;
@synthesize Apply;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_Scroller setScrollEnabled:YES];
    [_Scroller setContentSize:CGSizeMake(320, 2200)];

    [self dismissKeyboard];
    self.PositionLabel.text = job.position;
    self.RotationLabel.text = job.rotation;
    self.LocationLabel.text = job.location;
    self.TypeLabel.text = job.type;
    self.ClearanceLabel.text = job.clearance;
    jobPhoto.file = (PFFile *)job.imageFile;
    [jobPhoto loadInBackground];

    NSMutableString *pocText = [NSMutableString string];
    for (NSString* poc in job.poc) {
        [pocText appendFormat:@"%@\n", poc];
    }
    self.POC.text = pocText;

    NSMutableString *emailText = [NSMutableString string];
    for (NSString* email in job.email) {
        [emailText appendFormat:@"%@\n", email];
    }
    self.Email.text = emailText;


    NSMutableString *phoneText = [NSMutableString string];
    for (NSString* phone in job.phone) {
        [phoneText appendFormat:@"%@\n", phone];
    }
    self.Phone.text = phoneText;

    NSMutableString *applyText = [NSMutableString string];
    for (NSString* apply in job.apply) {
        [applyText appendFormat:@"%@\n", apply];
    }
    self.Apply.text = applyText;

    NSMutableString *qualificationsText = [NSMutableString string];
    for (NSString* qualifications in job.qualifications) {
        [qualificationsText appendFormat:@"%@\n", qualifications];
    }
        self.QualificationsTextView.text = qualificationsText;

    NSMutableString *job_descriptionText = [NSMutableString string];
    for (NSString* job_description in job.job_description) {
        [job_descriptionText appendFormat:@"%@\n", job_description];
    }
    self.Job_DescriptionTextView.text = job_descriptionText;
}



- (IBAction)favoriteButtonAction:(id)sender {
    PFObject *jobs = [PFObject objectWithClassName:@"Jobs"];
    PFUser *user = [PFUser currentUser];
    PFRelation *relation = [user relationForKey:@"Favorites"];
    [relation addObject:jobs];

    [user saveInBackground];



}


- (void)viewDidUnload
{
    [self setJobPhoto:nil];
    [self setPositionLabel:nil];
    [self setRotationLabel:nil];
    [self setLocationLabel:nil];
    [self setTypeLabel:nil];
    [self setQualificationsTextView:nil];
    [self setJob_DescriptionTextView:nil];
    [self setPOC: nil];
    [self setPhone:nil];
    [self setEmail:nil];
    [self setApply:nil];
    [self dismissKeyboard];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(void) dismissKeyboard {
    [Email resignFirstResponder];
    [POC resignFirstResponder];
    [Phone resignFirstResponder];
    [Job_DescriptionTextView resignFirstResponder];
    [QualificationsTextView resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) favoriteSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Added job to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}


- (void) favoriteFailed {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ooooops!" message:@"Error occurred while adding to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}



@end

JobListViewController that populates the jobs prior to the JobDetailViewController:

#import "JobDetailViewController.h"
#import "JobListViewController.h"
#import "Job.h"
#import "SearchedResultCell.h"
#import <Parse/Parse.h>



@interface JobListViewController () <UISearchDisplayDelegate, UISearchBarDelegate> {

}

@property (nonatomic, weak) IBOutlet UISearchBar *searchedBar;
@property (nonatomic, strong) NSString *mainTitle;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, assign) BOOL canSearch;

@end

    @interface JobListViewController ()

    @end

    @implementation JobListViewController
    {}
    @synthesize searchedBar;
    @synthesize mainTitle;
    @synthesize subTitle;
    @synthesize canSearch;


    - (id)initWithCoder:(NSCoder *)aCoder
    {
        self = [super initWithCoder:aCoder];
        if (self) {
            // Custom the table

            // The className to query on
            self.parseClassName = @"Jobs";

            // The key of the PFObject to display in the label of the default cell style
            self.textKey = @"Position";

            // Whether the built-in pull-to-refresh is enabled
            self.pullToRefreshEnabled = YES;

            // Whether the built-in pagination is enabled
            self.paginationEnabled = YES;

            // The number of objects to show per page
            self.objectsPerPage = 20;
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];



    }

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];

        self.canSearch = 0;

    }

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }

    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }

    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    - (void)objectsWillLoad {
        [super objectsWillLoad];

        // This method is called before a PFQuery is fired to get more objects
    }


    - (PFQuery *)queryForTable
    {
        PFQuery *query1 = [PFQuery queryWithClassName:@"Jobs"];
        NSString *searchThis = [searchedBar.text capitalizedString];
        [query1 whereKey:@"Position" containsString:searchThis];
        PFQuery *query2 = [PFQuery queryWithClassName:@"Jobs"];
        [query2 whereKey:@"Type" containsString:searchThis];
        PFQuery *query = [PFQuery orQueryWithSubqueries:@[query1,query2]];
            [query orderByDescending:@"createdAt"];

        if (self.pullToRefreshEnabled) {
            query.cachePolicy = kPFCachePolicyNetworkOnly;
        }

        // If no objects are loaded in memory, we look to the cache first to fill the table
        // and then subsequently do a query against the network.

        return query;
    }







    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
    {
        static NSString *simpleTableIdentifier = @"JobCell";
            static NSString *pimpleTableIdentifier = @"JobCell";

        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

        SearchedResultCell *bell = [self.tableView dequeueReusableCellWithIdentifier:pimpleTableIdentifier];

        if (bell == nil) {
            bell = [[SearchedResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pimpleTableIdentifier];

            }

            [self configureSearchResult:bell atIndexPath:indexPath object:object];


        }

        // Configure the cell
        PFFile *thumbnail = [object objectForKey:@"imageFile"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"AppIcon.png"];
        thumbnailImageView.file = thumbnail;
        [thumbnailImageView loadInBackground];

        UILabel *positionLabel = (UILabel*) [cell viewWithTag:101];
        positionLabel.text = [object objectForKey:@"Position"];
        UILabel *rotationLabel = (UILabel*) [cell viewWithTag:102];
        rotationLabel.text = [object objectForKey:@"Rotation"];
        UILabel *locationLabel = (UILabel*) [cell viewWithTag:103];
        locationLabel.text = [object objectForKey:@"Location"];
        UILabel *typeLabel = (UILabel*) [cell viewWithTag:104];
        typeLabel.text = [object objectForKey:@"Type"];


    return cell;
    }


    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"showJobDetail"]) {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

            Job *job = [[Job alloc] init];

            JobDetailViewController *destViewController = segue.destinationViewController;

            PFObject *object = [self.objects objectAtIndex:indexPath.row];
            job.position = [object objectForKey:@"Position"];
            job.poc = [object objectForKey:@"POC"];
            job.email = [object objectForKey:@"Email"];
            job.phone = [object objectForKey:@"Phone"];
            job.apply = [object objectForKey:@"Apply"];
            job.imageFile = [object objectForKey:@"imageFile"];
            job.rotation = [object objectForKey:@"Rotation"];
            job.location = [object objectForKey:@"Location"];
              job.type = [object objectForKey:@"Type"];
            job.clearance = [object objectForKey:@"Clearance"];
            job.job_description = [object objectForKey:@"Job_Description"];
            job.qualifications = [object objectForKey:@"Qualifications"];
            destViewController.job = job;

        }

    }

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {

        [self clear];

        self.canSearch = 1;

        [self.searchedBar resignFirstResponder];

        [self queryForTable];
        [self loadObjects];

    }



    - (void)configureSearchResult:(SearchedResultCell *)cell atIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
    {
        mainTitle = [object objectForKey:@"Position"];
        cell.mainTitle.text = mainTitle;

        subTitle = [object objectForKey:@"Type"];
        cell.detail.text = subTitle;

         // Implement this if you want to Show image
         cell.showImage.image = [UIImage imageNamed:@"AppIcon.png"];

         PFFile *imageFile = [object objectForKey:@"imageFile"];

         if (imageFile) {
         cell.showImage.file = imageFile;
         [cell.showImage loadInBackground];
         }
    }


    #pragma mark - UITableViewDelegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {



        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        [searchedBar resignFirstResponder];

        if ([self.objects count] == indexPath.row) {
            [self loadNextPage];
        } else {
            PFObject *photo = [self.objects objectAtIndex:indexPath.row];
            NSLog(@"%@", photo);

            // Do something you want after selected the cell
        }
    }



    #pragma mark - UIScrollViewDelegate


    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        [self.searchedBar resignFirstResponder];
    }

    - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        [self.searchedBar resignFirstResponder];
        [self queryForTable];
        [self loadObjects];

    }







    @end

Update image of UIImageView in NSmutableArray?

I have:

Class Piece inherit UIImageView;

- (void)setJumpAt:(int)frame {
NSMutableArray *ret = [SkinConstants BallSelected];
NSString *name = [NSString stringWithFormat:@"balls-%d-%d", color - 1, [[ret objectAtIndex:frame] intValue]];
UIImage *a = [UIImage imageNamed:name];
NSLog(@"%d setJumpAt: %@", self.tag ,name);
[self performSelectorOnMainThread:@selector(setImage:) withObject:a waitUntilDone:NO];
[self  setNeedsDisplay];
[self setNeedsLayout];}

Class Player contain NSMutableArray of Piece;

Class JumpThread contain NSTimer use to set image of Piece;

- (void) timer_Tick{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
        [piece setJumpAt:frame++];
        [piece setNeedsDisplay];
        if (frame == len)
            frame = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
    });
});}

I run code normal, but image of Piece not change in mainview, Sorry, I'm not so good at English.

Create a Url shortcut in Xcode using Objective c

In my app users can upload images to my website and they can share the link. What I need to do is to create a link shortcut.

For example I have this link: (http://ift.tt/1dpVk0W)

i need to change the link to (for example): wedv.ghfi

is it possible to do it?

Thanks

Can cocos-2dx play a song from the phone's library?

I'm using an MPMusicPlayerController to access and play music in an objective C file, but I need to play it in my C++ file using SimpleAudioEngine. Is it possible to select an item with MPMusicPlayerController and use its URL(ipod-library://item/item.m4a?id=456458322781804615) to play the music?

Deterministic shuffle in Objective C

This code in Java is the implementation of Knuth's shuffle, but a deterministic one, controllable by the seed to the random number generator.

public String shuffleString(String data, long shuffleSeed) {
    if(shuffleSeed!=0) {
        Random rnd = new Random(shuffleSeed);
        StringBuilder sb = new StringBuilder(data);
        int n = data.length();
        while(n>1) {
            int k = rnd.nextInt(n--);
            char t = sb.charAt(n);
            sb.setCharAt(n, sb.charAt(k));
            sb.setCharAt(k, t);
        }
        return sb.toString();
    }
    else {
        return data;
    }
}

How can I implement a deterministic shuffle in Objective C that outputs the same shuffle order given the same seed? I am using srandom(_shuffleSeed); and random()%(n--) knowing that arc4_random is better but that cannot be seeded.

- (NSString*) shuffleString:(NSString*) data withShuffleSeed:(int) shuffleSeed {
    if(shuffleSeed!=0) {
        srandom(_shuffleSeed);
        NSMutableString *result = [[NSMutableString alloc] initWithString:data];
        unsigned long n = data.length;
        while(n>1) {
            unsigned long k = random()%(n--);
            unichar t = [result characterAtIndex:n];
            NSRange r1 = {n,1};
            [result replaceCharactersInRange:r1 withString:[NSString stringWithFormat:@"%c", [result characterAtIndex:k]]];
            NSRange r2 = {k,1};
            [result replaceCharactersInRange:r2 withString:[NSString stringWithFormat:@"%c", t]];
        }
        return result;
    }
    else {
        return data;
    }
}

Currently, the two shuffle methods do not generate the same result for the same input parameters. I am sure I am missing something!

Stop NSRunloop in NSOperate

I Know is maybe a bad design,but all i want to do is run a nsTimer in NSOperation,so here is what i done:

            #import "CountOperate.h"

            @interface CountOperate ()

            @property(nonatomic, strong) NSTimer *timer;
            @property(nonatomic, unsafe_unretained) NSInteger repeatSecond;

            @end

            @implementation CountOperate

            - (void)main
            {
                self.repeatSecond = 15;

                self.timer = [NSTimer timerWithTimeInterval:self.repeatSecond target:self selector:@selector(update) userInfo:nil repeats:YES]; 
                [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; 
                [[NSRunLoop currentRunLoop] run]; 
            }

            - (void)cancel
            {
                [self.timer invalidate];
                [super cancel];
            }

            - (void)update
            {
                NSUInteger myRandom = arc4random_uniform(100);
                self.dateArray[self.myID] = @(myRandom);     
                [self.tableView performSelectorOnMainThread:@selector(reloadData)
                                                 withObject:nil
                                              waitUntilDone:NO];
                [[NSRunLoop currentRunLoop] performSelector:@selector(update) withObject:nil afterDelay:self.repeatSecond];
            }

The problem here is that I can not stop it immediately, it must wait to be completed after the completion of the interval timer, it's like NSRunLoop must run until the next time the timer fires .

In this example,i had wait 15second,so i can see the NSOperation has finish its job.

NSClassFromString with String coming from Plist

I'm trying to instanciate a class in Swift from a String, ok it can sound weird but the ClassName comes from a Plist.

I'm using NSClassFromString but it doesn't work with the Plist String, I think that I'm close to this question: NSClassFromString works for string literals, returns nil for constructed strings

But I can't use the solution as I can't know the possible classname coming from the Plist

The weird behavior is that if I create the String manually in the code, with the same value then it works as expected... it's like the converted String from the Plist is not the real exact same thing as a new String.

There is the code

let className: String = definition["class"] as! String
let classNameManually: String = "AppName.ServiceTest"
let aClass = NSClassFromString(className) as! NSObject.Type
let instanceObject = aClass()

It works with classNameManually but not with className

Then I put a breakpoint and I have identified a slighly difference

DebugView

Do you have a magic answer ?

Thank you!

save backgroundColor with NSUserDefaults

I tried to save what user choose color from Plain Segmented Control in objective-c with this code but it doesn't working

for saving

   UIColor *saveColor = changeColor.backgroundColor;
   NSUserDefaults *Color = [NSUserDefaults standardUserDefaults];
   [Color setObject:saveColor forKey:@"saveColor"];
   [Color synchronize];

for loading

   NSUserDefaults *color = [NSUserDefaults standardUserDefaults];
   UIColor *loadColor = [color objectForKey:@"saveColor"];
   [changeColor setBackgroundColor:loadColor];

Replace Placeholder Content in PDF iOS

I have looked at the other questions similar to this one, such as how to edit a PDF in objective-c? and iOS - searching and replacing on a PDF; however I have not found an answer that seems to work.

I have a PDF with the placeholder [text1], and I would like to replace this with a string that I receive from user input and then display the updated PDF.

2 Notes:

Apple's PDFkit appears to be only available in OS X, and I have been unable to locate an iOS library that has this functionality.

I don't believe that this PDF would be easy to generate from an HTML template.

Is there a way to do this (in either Swift of ObjC)?

Loop formatting

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSInteger n = 5;
     NSInteger nFactorial = n;
     while (n > 1) {
         nFactorial = nFactorial * --n;
     }
     NSLog(@"The factorial of %ld is %ld", (long)n, (long)nFactorial);
     return YES;
 }

For this code, why does nFactorial have to be initialized to n? Why can't the code just use n in all the places that have nFactorial in it?

Subclassing UITableViewCell & [tableView dequeueReusableCellWithIdentifier:CellIdentifier]

I'm trying understand how [tableView dequeueReusableCellWithIdentifier:CellIdentifier] works. Here is my situation:

I have designed my UITableViewCell subclass in IB and now I'm trying style my sub elements of the cell in my subclass. Unfortunately the method [tableView dequeueReusableCellWithIdentifier:CellIdentifier] seems to not call any method in my cells subclass. With methods I mean initWithCoder,initWithFrame or init.

This is my actual code:

static NSString *BasicCellIdentifier = @"BasicCell";
GSFeedBasicTableViewCell *basicCell = [tableView dequeueReusableCellWithIdentifier:BasicCellIdentifier];

My Cells are showing up but I would to customize the cell further in my subclass to avoid styling code in my TableController. Any hints are really appreciated.

NSDictionary and NSPredicate

I am using a NSDictionary that itself contains dictionaries some keys and its values which are arrays.The format is like so:

{
    0 =     {
        0 =         (
                     3,
                     0,
                     3
                     );
        1 =         (
                     2,
                     0,
                     2
                     );
    };
    1 =     {
        0 =         (
                     1,
                     1,
                     1
                     );
        1 =         (
                     1,
                     1,
                     2
                     );
    };
};

I'm using NSPredicate to searach a dictionary within the dictionary to get the array that contains value 3 at index 0. like so:

inside = [VDictionary objectForKey:[NSNumber numberWithInt:0];
NSPredicate *p = [NSPredicate predicateWithFormat:@"%@[SELF][0] == '3'", inside];

It works but the problem is that the above only searches the dictionary with key 0, I want to search all the dictionaries not just one at a time.

How do I use NSPredicate to search all the dictionaries within a dictionary and get the array that contains the value 3 at index 0?

iOS app single table view cell not functioning

I am using the storyboard feature in Xcode, and I wanted to add a switch for if the order was a credit card. I have seen in other apps a switch is usually in a single table view cell. I tried to implement it on the storyboard, (the second scene of the app) and whenever I go to that scene in the simulation, it crashes with this message:(I cannot post a picture, if you would like one email me at zacharymanno@gmail.com) 2015-06-27 20:07:33.233 ToDoList[9048:436904] * Assertion failure in -[UITableViewCell _setHostsLayoutEngine:], /SourceCache/UIKit_Sim/UIKit-3347.44/NSLayoutConstraint_UIKitAdditions.m:2761 2015-06-27 20:07:33.268 ToDoList[9048:436904] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Must translate autoresizing mask into constraints to have _setHostsLayoutEngine:YES.'

Check for local notifications settings from extension

Is it possible to check for the current Local Notifications settings inside a Cocoa Touch Framework used by an extension?

Usually I’d use

    var currentStatus:UIUserNotificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings()

… but access to UIApplication.sharedApplication() is not available as extension safe API.

Any alternative?

Get multiple selected rows info of an uitableview

I have so far a tableView that works with multiple selection rows. Everything is working fine except when I'm trying to get an array of the rows that I've selected.

var currentStat = Stat()
var selectedMarks = [StatEvents]()

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.font = UIFont.systemFontOfSize(8.0)
    cell.textLabel?.text = "\(currentStat.statEvents[indexPath.row].name)  \(currentStat.statEvents[indexPath.row].dateRanges) horas=\(currentStat.statEvents[indexPath.row].hours)"

    if currentStat.statEvents[indexPath.row].isSelected{
        cell.accessoryType = .Checkmark

    } else {
        cell.accessoryType = .None
    }
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: false)
    currentStat.statEvents[indexPath.row].isSelected = !currentStat.statEvents[indexPath.row].isSelected

    if (selectedMarks.contains(currentStat.statEvents[indexPath.row])){
        selectedMarks.removeAtIndex(indexPath.row)
    } else {
        selectedMarks.append(currentStat.statEvents[indexPath.row])
    }
    tableView.reloadData()
}

The problem is in the "didSelectRowAtIndexPath" method. When I select any row, it appends the object in the "selectedMarks" array (this is working fine), but the problem is when I deselect some of those rows, it should erase back the object in the selectedMarks array. I'm trying to use the "contains" method, but I get a compilation error in that line

could not find an overload for contains that accepts the supplied arguments

Somebody knows how do I solve this? Probably there's another way to get the selected rows array info...

Loading GameCenter Log-in in ViewDidLoad

I researched Apple's documentation for GameCenter, but when I tried to implement their sample code, it did not work. Am I doing something incorrectly?

 - (void)viewDidLoad {
[super viewDidLoad];

 GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];
if (gameCenterController != nil)
{
   gameCenterController.gameCenterDelegate = self;
   [self presentViewController: gameCenterController animated: YES completion:nil];
}
}

I am trying to load the sign in for gamecenter right when the user opens the app. Thank you

Swift / Objective-C integration w.r.t. ARC

I'm having trouble with the integration of Objective-C and Swift. The Objective-C code uses MRC (not ARC). To boil down the issue to a simple example, imagine that I have an objective-C object that owns lots of other objects embedded in its state. It provides methods to return pointers to objects it owns. Since it does not relinquish ownership, all of these objects do not see retain or autorelease messages when they are being returned.

The flow of control takes me through code in this order

A (objective-C) calls B (Closure in Swift) and B calls C (method in Objective-C)

The sequence of calls is supposed to get a value (pointer to object) from the call to C.

Imagine that the big container class has a method (C above)

-(id)getObject:(NSUInteger)identifier

The method has been tagged for swift with:

-(__unsafe_unretained id)getObject:(NSUInteger)identifier

to indicate that the object returned should not be subjected to ARC (at least, that was my hope... It does not seem to be the case).

Now, I write a closure in swift as follows (I simplified to keep the essence) (That's B in the example):

{ k -> container.getObject(k) }

And that closure is passed to Objective-C code (A in the example) and is being called from objective-C. What I was hoping for is: no ARC "interference". But that's not the case! If I rewrite the swift closure to:

{ k -> unowned let rv = container.getObject(k); return rv}

Things are a little better (retain/release calls originating from swift code disappear), but I still get into trouble, because it seems that the compiler creates another Objective-C Block to bridge with Swift closures.

See the fragment below (lifted from lldb backtrace)

#0  0x0000000100159210 in partial apply forwarder for queensNaiveSwift.(closure #1).(closure #4) ()
#1  0x000000010015b627 in reabstraction thunk helper from @callee_owned () -> (@owned ObjectiveC.ORIntVar) to @callee_unowned @objc_block () -> (@autoreleased ObjectiveC.ORIntVar) ()

There is this "Reabstraction thunk helper" which (as I understand it) is a compiler generated objective-C block that wraps the Swift closure. As you see, its 'type' betrays the fact that the return value (type ORIntVar in reality) is @autoreleased. Looking at the assembly confirms that there is a call to autorelease. But the entire thing was written to avoid ARC. Bottom line, the thunk helper is sending my object an autorelease. That puts the object in a global auto-release pool (which defeats the purpose and delays the release). Adding a temporary autoreleasepool is not the solution here. I simply do not wish to receive retain/release/autorelease.

So... How do I tell the Swift compiler to not generate auto-release in its thunks? The value coming back is __unretained_unsafe (and unowned in Swift). Why does the thunk feel compelled to do anything with this pointer? It should be a simple pass-through, no funny business. (Also, I'd rather avoid being forced to pepper the Swift code with unowned let x = ...

Any hint/explanation is much appreciated.

Custom font set in a storyboard won't display on device

I created a label in LaunchScreen.storyboard and used a custom font. It looks all right in xcode but when I run the program on my device or simulators it won't display the custom font. I've already added the font file to the project and the font name to the "Fonts provided by application" array in info.plist. The font file is also added to "Copy Bundle Resources". I've tried all the solutions provided in some other similar questions but none of them worked so I'm not asking a repeated question.

Failed to Import Bridging Header Error

I accidentally messed up my projects' settings while installing and then uninstalling cocoapods. I'm now getting the error "failed to import bridging header". I checked my build settings and the path to the file under build settings > code generation > objective-c bridging header is correct. I messed around with my Framework Search Paths (they are empty now) in build settings while trying to get cocoapods to work. Would really appreciate some help on fixing this bridging header issue.

Instruments memory leaks detecting issue in Xcode 6.2

everyone! I'm using Xcode 6.2 now for developing objective-c, when i try to use "Instruments" to detecting memory issues, it just not work as i were see books or blogs.I use the code blow to test(main function is omitted, using default xcode&instruments settings).

for(int i=0; i<2; i++)
{
    KSTestObj *obj0 = [[KSTestObj alloc] init];
    KSTestObj *obj1 = [[KSTestObj alloc] init];
    obj0.obj = obj1;
    obj1.obj = obj0;
}
sleep(100);

and the KSTestObj class just has a NSObject propety. Here is a strange phenomenon. When I set i<1, the "Instruments" capture nothing, and when i<2(or bigger), it can detect a memory problem by Leaks! BUT the leaked objects number is 2(or 2*times-2)!Thats ODD! Anyone knows what going on? Did i made any mistakes? tks! here is the picture & log: i<2, and "Instruments" detect 2 object leaked.

2015-06-27 14:33:19.108 ObjCPro_Test[50820:603] init success! 0x7ff968700c10
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff968700c20
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff9687003a0
2015-06-27 14:33:19.110 ObjCPro_Test[50820:603] init success! 0x7ff9687003b0
<End of Run>

enter image description here

i<1, "Instruments" shows no leaked objects!

2015-06-27 14:30:17.737 ObjCPro_Test[50789:603] init success! 0x7f7ff1e00830
2015-06-27 14:30:17.738 ObjCPro_Test[50789:603] init success! 0x7f7ff1e004e0
<End of Run>

enter image description here

Is the navigation controller's root view controller the same as that of the window's when set?

Just a question I have that doesn't appear to have been directly answered here before.

I have a simple app using storyboard which has a navigation controller set as the initial view controller in the storyboard, and the first view controller set as the navigation controller's root view controller.

I've read that the window has exactly one root view controller. Is that, then, in this case the navigation controller itself, since it's the initial view controller, or does the window share the navigation controller's root view controller?

Thanks in advance for any help.

Handling scrolling nested UIScrollViews scrolling in the same direction

I am trying to implement something similar to Twitter iOS App (profile page)

This is view hierarchy:

  • UIScrollView

    • Custom View
    • UITableView

    During scroll, once UIScrollView reaches certain y offset, (when UITableView gets to the top of the screen), then UITableView should start scroll. This needs to work in one continuous motion.

By default, this is not in continuous motion.

Disable SWRevealViewController bouncing on addGestureRecognizer

I'm trying to use SWRevealViewController in my app which is sliding menu library, but i needed to edit the library with one option and i will explain as follows. when using addgestureRecognizer and opening the sliding-menu by keep on holding from the left to the most right and then left it,it bounce too much outside to the right then close the menu. i just need to disable this option from the library, just like to open to its normal limit without bouncing.

The link on GitHub is here : http://ift.tt/Jtzjj8

IOS line measurement on picture

I need some help to get started on drawing lines with circle at ends, and measure its length. I am able to draw the line but can't make it moving,having spent hours decided to post on SO.

So please see below image and guide me to get started. Any sample or tutorial using objective c will help.

enter image description here

EDIT: The answer posted by ndmeiri is making use of multi touch. It is really great but unfortunately this has to be achieved without making use of multi touch. The scenario is, at any given time there will be some flexible lines available on screen. User can just drag any end point to resize the line in any direction. I can't get this thing working correctly..

Here is my gist file, code allows me to resize the line with touch points but doesn't allow to change the angle of line and adding text in centre. http://ift.tt/1dp9Hm0

Any help is highly appreciated. Thanks :)

Hit button once to show UIImage. Hit button again to hide UIImage

i researched on this website but couldn't find anything to help me. I'm a beginner in coding so this may seem simple to some of you but hard for me. I have an instruction button in my game that i press to show a speech bubble giving the user instruction, i would like it so when i repress the instruction button, the speech bubble disappear.

.h

IBOutlet UIImageView *instructionsPic;
- (IBAction)instructionAction;

.m

- (IBAction)instructionAction {
instructionsPic.hidden = NO;
startGameButton.hidden = YES;

}

In my viewDidLoad i marked my instruction bubble speech as hidden and when the user hits the instruction button it shows up. So yea, how can i make it disappear again when they click the button again?

Thank you (:

Add calendar to iOS app

I am attempting to create an app of events where I add an event to my online database and it is added to the calendar of my application. So example, If i add "Party on the beach" in my db,set date to 25th June 2015. A user opening the application and navigating to "Events..selecting June" will see this on a calendar.

I am having a little trouble implementing something of the sort as all searches is leading me of how to sync my app with the native calendar app of the device which is not exactly what I want.

Basically I just want a calendar in my app which reads events from online.. Any assistance to point me in the right direction would be appreciated.

Edit I have a hosted database, what I am looking to find is some calendar that can read events from said database.

convert api string to JSON in swift or objective-c

hi i'm getting following string(text/html) not (text/JSON) when make api request.

 let request = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    let res =   NSString(data: data, encoding: NSUTF8StringEncoding)!
        var jsonStr = res

        //here 'res' will be {status: 1, userid: "447", store_code: "930"}

        var data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
        var localError: NSError?
        var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError)

        println("json res \(json)") // 'json' here is nil

        if let dict = json as? [String: AnyObject] {
             let weather = dict["status"] as? [AnyObject]
                println(weather)

        }

    }

//following is the text/html response from api request

{status: 1, userid: "447", store_code: "930"}

So how can i convert this text/html string to JSON.When i try to use NSJSONSerialization it gave fatal error or nil. Can anybody help me how can i solve this issue in swift or objective-c?

randomly change image of buttons and decelerate changing

i have 2 buttons.

they are called _rightButtonPressed and _leftButtonPressed. They have an background image named "blackBackground". When they are clicked, the background image is changed to "whiteBackground".

Ok. Now i want to make a third button, that changes the background image at first _rightButtonPressed to "white", then "black", then _leftButtonPressed to "white", then "black" and so on. This change have to decelerate to the end. At least, it should be randomly stops at a button with "white" background image and click the button. I hope its comprehensible.

I have no idea, how i can do this...

When programatically creating a ViewController, how can I set its view to be of type SKVIew?

I am developing a game in iOS on XCode. I have several SKScenes each associated with a UIViewController class. So in each of the view controller's viewDidLoad, I create

SKView *skView = (SKView *)self.view
SKScene * scene = [whateverSKScene sceneWithSize:skView.bounds.size]
[skView present scene]

I want to avoid the storyboard. However, when I presentViewController from the first view controller to the next, the app crashes at the line "[skView present scene]" because it thinks the new view controller's view is still UIView ('-[UIView presentScene:]: unrecognized selector sent to instance).

How can I fix this? Specifically, when creating the 2nd view controller (programatically), how can I change its view to be of type SKview not UIview? (I should note I want the scenes to be 1:1 with view controllers because almost all of them are popups like a pause-menu pop up over game play or settings pop up etc)

UIAlertView in superclass and subclass

I have a superclass where I sometimes show an UIAlertView and handles the delegation (clickedButtonAtIndex). When I then have a subclass that also handles the "clickedButtonAtIndex" only the subclass delegation is called.

In both cases the UIAlertView is show like this:

[[[UIAlertView alloc] initWithTitle:@"" message:@"message" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:@"Open", nil]show];

Am I doing something wrong or is it bad design to have the same delegation in both the superclass and subclass. I thought the "delegate:self" separated them.

How to convert UPC-A to UPC-E?

We would like to convert the 12 digit UPC-A to 8 digit UPC-E. Can you tell me which is the best way to do this without having to use my own code to convert?

I got many formula for convert the 8 digit UCC-E to 12 digit UPC-A but not reverse.

IOS: keyword search in a list of passages only returns the last match, instead of all matches

i have one passage list and from that i want to find out keyword search from user, passage ID getting over ride in array and because of that only last passage showing the result.

i want search keyword from all passage and show the result .

- (UIViewController*) showContentWithQuery:(NSDictionary*)query
{
ContentViewController * viewController = nil;
if (query)
{

    NSNumber * sectionId = query[@"sectionId"];
    NSNumber * passageId = query[@"passageId"];

    if (sectionId)
    {
        viewController = [[[ContentViewController alloc] initWithSectionId:sectionId] autorelease];

        if (passageId)
        {

            viewController.tempHighlightPassageArray = @[passageId];
        }
    }
}

return viewController;     }

iOS and unicode characters: \u+2605 not solid star in UILabel

I'm trying to make a UILabel that says "★ FEATURED". However, when it renders it, the star isn't solid! Here's the code I'm using:

    _sponsoredLabel = [UILabel new];
    _sponsoredLabel.numberOfLines = 1;
    _sponsoredLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _sponsoredLabel.textColor = [UIColor yellowColor];
    _sponsoredLabel.backgroundColor = [UIColor clearColor];
    _sponsoredLabel.textAlignment = NSTextAlignmentLeft;
    _sponsoredLabel.text = @"✭ FEATURED";
    _sponsoredLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0f];
    _sponsoredLabel.hidden = YES;

In the text itself it looks solid, but here's what it looks like when it renders:

Any advice is much appreciated!

Delay in Corelocation

I've created a helper class for my location needs so i don't violate the DRY principle. The class looks like this:
Location.h

@interface Location : NSObject <CLLocationManagerDelegate>{
CLLocationManager *manager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}

-(float)latitude;
-(float)longitude;
-(NSString *)postalcode;

Location.m

@implementation Location{
    float latitude;
    float longitude;
    NSString *postalcode;
}
-(id)init{
    NSLog(@"Hallo");
    [self setupLocationManager];
    return self;
}

-(float)latitude{

    return latitude;
}

-(float)longitude{

    return longitude;
}

-(NSString *)postalcode{

    return postalcode;
}

-(void)setupLocationManager{
    manager = [[CLLocationManager alloc] init];
    [manager requestWhenInUseAuthorization];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.distanceFilter = 100;
    [manager startUpdatingLocation];
    geocoder = [[CLGeocoder alloc] init];
 }

 #pragma mark - CLLocationManagerDelegate Methods

 - (void)locationManager:(CLLocationManager *)manager didFailWithError:          (NSError *)error
{

     NSLog(@"Error: %@", error);
     NSLog(@"Failed to get location! :(");

}

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

NSLog(@"Location: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {

    latitude = currentLocation.coordinate.latitude;
    longitude = currentLocation.coordinate.longitude;


}

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

    if (error == nil && [placemarks count] > 0) {

        placemark = [placemarks lastObject];
        postalcode = [NSString stringWithFormat:@"%@",placemark.postalCode];
        /*
         self.address.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
         placemark.subThoroughfare, placemark.thoroughfare,
         placemark.postalCode, placemark.locality,
         placemark.administrativeArea,
         placemark.country];
         */
    } else {

        NSLog(@"%@", error.debugDescription);

    }

} ];

}


 @end

When i in my ViewController tries to create an instance of Location and set latitude and longitude labels, in the viewDidLoad method, the labels are sat to 0.00000. Apparently it takes around half a second for Location to get the coordinates. I've tried using

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self setCoordinateLabels];
    });

But that just seems very hacky and can't possibly be the best practise? So is there any way i could do this a better way?

Saving OS X Game Data Using NSData and NSMutableArrays

I am trying to store the hi-score of several levels in a NSMutableArray, which will then be saved in a file in the Documents folder. I know I can use plists, but I don't want the content to be modified by the user. It appears that NSMutableArray *hiscore is not being initialized and I'm not sure how to fix this. For primitives it seems fine, but for objects it's not working.

GameData.h

@interface GameData : NSObject <NSCoding>

@property (assign, nonatomic) int level;
@property (assign, nonatomic) NSMutableArray *hiscore;

+(instancetype)sharedGameData;
-(void)save;
-(void)reset;

@end

GameData.m

#import "GameData.h"

@implementation GameData

static NSString* const GameDataLevelKey = @"level";
static NSString* const GameDataHiscoreKey = @"hiscore";

- (instancetype)initWithCoder:(NSCoder *)decoder {
    self = [self init];
    if (self) {
        _level = [decoder decodeDoubleForKey: GameDataLevelKey];
        _hiscore = [decoder decodeObjectForKey:GameDataHiscoreKey];
    }
    return self;
}

+ (instancetype)sharedGameData {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [self loadInstance];
    });

    return sharedInstance;
}

+(instancetype)loadInstance {
    NSData* decodedData = [NSData dataWithContentsOfFile: [GameData filePath]];
    if (decodedData) {
        GameData* gameData = [NSKeyedUnarchiver unarchiveObjectWithData:decodedData];
        return gameData;
    }

    return [[GameData alloc] init];
}

-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeDouble:self.level forKey: GameDataLevelKey];
    [encoder encodeObject:self.hiscore forKey:GameDataHiscoreKey];
}

+(NSString*)filePath {
    static NSString* filePath = nil;
    if (!filePath) {
        filePath =
        [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
         stringByAppendingPathComponent:@"gamedata"];
    }
    return filePath;
}

-(void)save {
    NSData* encodedData = [NSKeyedArchiver archivedDataWithRootObject: self];
    [encodedData writeToFile:[GameData filePath] atomically:YES];
    /*[_hiscore writeToFile:[GameData filePath] atomically:YES];*/
}

-(void)reset {
    self.level = 0;
}

@end

LevelScene.m

#import "GameData.h"
...
[[[GameData sharedGameData] hiscore] addObject:@1500];
[[GameData sharedGameData] save];

Correct pattern for mutable vs immutable

I'm wondering what the correct pattern for implementing Mutable vs Immutable data structures would be. I understand the concept and how it works, but how should I implement if using an underlying Cocoa data structure? I mean, if I use a NSSet, for instance. Lets say I have the following:

// MyDataStructure.h
@interface MyDataStructure : NSObject
@property (nonatomic, strong, readonly) NSSet * mySet;
@end


// MyDataStructure.m
@interface MyDataStructure ()
@property (nonatomic, strong) NSMutableSet * myMutableSet;
@end

@implementation MyDataStructure

- (NSSet *)mySet
{
    return [_myMutableSet copy];
}

@end

The only reason I'm using a mutable set as the underlying data structure,is so that the mutable version of this class can tamper with it. MyDataStructure per se does not really need a mutable set. Therefore, assuming that I have implemented some initialisers to make this class useful, here's how MyMutableDataStructure looks like:

// MyDataStructure.h (same .h as before)
@interface MyMutableDataStructure : MyDataStructure

- (void)addObject:(id)object;

@end

// MyDataStructure.m (same .m as before)
@implementation MyMutableDataStructure

- (void)addObject:(id)object
{
    [self.myMutableSet addObject:object];
}

@end

By using this pattern the underlying data structure is always mutable, and its immutable version is just an immutable copy (or is it??).

This also begs another question that arises when implementing the NSCopying protocol. Here's a sample implementation:

- (id)copyWithZone:(NSZone *)zone
{
    MyDataStructure * copy = [MyDataStructure allocWithZone:zone];
    copy->_myMutableSet = [_myMutableSet copyWithZone:zone];

    return copy;
}

Doesn't copyWithZone: return an immutable copy if that applies? So I'm basically assigning a NSSet instead to a NSMutableSet property, isn't that right?

Edit: While diving deeper into the issue I found some more issues surrounding this concern.

  1. mySet should be copy instead of strong.
  2. My copyWithZone: implementation isn't right either. I didn't mention it in the first post but that implementation relates to the Immutable version of the data structure (MyDataStructure). As I've read, Immutable data structures don't actually create a copy, they just return themselves. That makes sense.
  3. Because of 2., I needed to override copyWithZone: in the Mutable version (MyMutableDataStructure).

To make things clear:

// MyDataStructure.h
@property (nonatomic, copy, readonly) NSSet * mySet;

And

// MyDataStructure.m
@implementation MyDataStructure

- (id)copyWithZone:(NSZone *)zone
{
    // We don't really need a copy, it's Immutable
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    // I also implement -mutableCopyWithZone:, in which case an actual (mutable) copy is returned
    MyDataStructure * copy = [MyMutableDataStructure allocWithZone:zone];
    copy-> _myMutableSet = [_myMutableSet mutableCopyWithZone:zone];

    return copy;
}

@end

@implementation MyMutableDataStructure

- (id)copyWithZone:(NSZone *)zone
{
    return [self mutableCopyWithZone:zone];
}

@end

It seems tricky at first, but I think I'm getting the hang of it. So the remaining questions are:

  1. Is the pattern correct?
  2. Does the getter for mySet return a mutable or immutable instance?
  3. (not listed before) Do I really need the copy signal when using the copy property attribute?

I appreciate your patience to read this far. Best.

Sharing of Image and text with Deep linking on facebook in ios8

Have anyone worked on deep linking in ios 8? I tried to follow facebook.developer tutorial to implement deep linking but is not so much clear. please suggest me any blog and tutorial or sample code. Any help will be appriceate. Thanks in advance!

How to change duration of ImageView in Objective-C

I am creating a simple camera app for a photobooth. This code below is a sample of the whole project, I am using AVFoundation because I needed my own custom requirements.

When the user presses a button, it takes a photo and instantly shows the preview in the imageView. This is my first major coding project and am new to Objective-C. Is there a way to add a timer or duration to the imageView so that it then removes the image from it, or a way to cycle to a second black image after some time, ready for the next user to take their photo?

Many thanks for any help suggested!

- (IBAction)takephoto:(id)sender {

    AVCaptureConnection *videoConnection = nil;

    for (AVCaptureConnection *connection in StillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts ]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
    }
    [StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer != NULL) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            imageView.image = image;
        }
    }];
}

How to add collection view programmatically in iOS

i want to add UICollectionview when i click on a button.. The default screen has table view already. I am adding grid option button and want to arrange data in grid by collection view when user click on grid button

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.