samedi 25 avril 2015

UITableView doesn't refresh when NSPredicate set


Preface: I tried [self.tableview reloadData]. My app doesn't crash, but it doesn't refresh, either.

I'm trying to display 2 sets of results on one TableViewController depending upon whether an NSPredicate is set. I'm trying to find a jargon free answer how I can update a UITableViewController once a predicate is set.

My data displays properly the when the view initially loads. My predicate sets properly, all the log statements I've thrown in return values...but nothing happens when it's set.

I know this is a startlingly stupid question, but I'm too dumb figure it out. Every answer I've found involves a UISearchBar, deprecated methods, or is a snippet of an answer, etc.

What I'd like to display:

1) A vanilla fetchRequest that displays everything--this works: everything in my managedObjectContext which is set up in my viewDidLoad w/o an NSPredicate.

2) Once I set an NSPredicate, I'd like to update the tableView--This doesn't crash, but it doesn't update the tableView

On MyTableViewController, I have a popover which instantiates when I click a UIBarButtonItem on MyTableViewController. On the popover, I set a predicate on MyTableViewController.

Basically, I'd like to toggle what's displayed and that display toggle is driven by whether my variable is nil (everything displays) or filtered (variable sets a predicate).

I'm either the first or the dumbest person to attempt this feat of software engineering. I'll wager the latter, given how many times I've seen this as an end-user. If you know what I'm doing wrong, I'd be grateful to hear from you. Thank you for reading.

I have two entities: PointOfInterest and LocationCategory. I have a UIBarButton that triggers a popover of which MyTableViewController is a delegate. Clicking on the popover sets the selectedCategory property on MyTableViewController.:

// This gets set by PopoverTableViewController    
@property (nonatomic, strong) LocationCategory *selectedCategory;     

// This is set on `MyTableViewController`
@property (nonatomic, strong) NSPredicate *searchPredicate;

The property gets set correctly on MyTableViewController. I'm trying to use the selectedCategory object as the basis for a predicate to display "filtered" list of 'pointOfInterest' objects. I left out the boilerplate code from this TVC, but I've got the tableView delegate methods on the TVC.

I think I need to set my fetchedResultsController to nil and reinstantiate it w/ a predicate in my refreshTableViewController method. It doesn't crash, but it doesn't work, either.

Here's the viewDidLoad of MyTableViewController:

- (void)viewDidLoad {
    [super viewDidLoad];

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    self.managedObjectContext = appDelegate.managedObjectContext;

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    NSLog(@"savedPOI managedObjectContext is %@", self.managedObjectContext);

    // Initialize fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"PointOfInterest"];

    // Add sort descriptors
    [fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];

    // Initialize Fetched Results Controller
    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

    // Configure a fetchedResultsController
    [self.fetchedResultsController setDelegate:self];

    // Perform fetch
    NSError *error = nil;
    [self.fetchedResultsController performFetch:&error];

    if (error) {
        NSLog(@"Unable to perform fetch");
        NSLog(@"%@, %@", error, error.localizedDescription);
    }

    // This sets up an observer that listens for when `selectedCategory` is set
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTableViewController:) name:@"CategorySelected" object:nil];    
}

Once my selectedCategory is set, I have the following method set to run. It doesn't crash, but it doesn't refresh MyTableViewController. I suspect I've got a minor error here, but I'm not sure what I'm doing wrong.

- (void)refreshTableViewController:(NSNotification *)notification {
    if ([[notification name]isEqualToString:@"CategorySelected"]) {
        NSLog(@"NSNotification on SavedPOITableViewController's self.selectedCategory is %@", self.selectedCategory.categoryName);

        // Nuke the cache that was loaded in viewDidLoad
        [NSFetchedResultsController deleteCacheWithName:@"PointOfInterest"];

        // Nuke the fetchedResultsController alloc/inited in viewDidLoad
        self.fetchedResultsController = nil;

        // Alloc init a new fetchRequest
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

        // Set the entity
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"PointOfInterest" inManagedObjectContext:self.managedObjectContext];
        [fetchRequest setEntity:entity];

        // Add sort descriptors
        [fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];

        // Reinstantiate the fetchedResultsController
            self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

        NSString *predicateString = self.selectedCategory.categoryName;
        NSLog(@"predicateString is %@", predicateString);

        self.searchPredicate = [NSPredicate predicateWithFormat:@"locationCategory.categoryName == %@", predicateString];
        NSLog(@"self.searchPredicate in refreshTableViewController is %@", predicateString);

        // Do the fetchRequest with the predicate
        [fetchRequest setPredicate:self.searchPredicate];

        // Perform fetch
        NSError *error = nil;
        [self.fetchedResultsController performFetch:&error];

        if (error) {
            NSLog(@"Unable to perform fetch");
            NSLog(@"%@, %@", error, error.localizedDescription);
        }
        [self.tableView reloadData];        


    }
}

Just for completeness' sake, here's my PointOfInterest & LocationCategory classs:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class LocationCategory;

@interface PointOfInterest : NSManagedObject

@property (nonatomic, retain) NSString * note;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * address;
@property (nonatomic, retain) NSNumber * latitude;
@property (nonatomic, retain) NSNumber * longitude;
@property (nonatomic, retain) NSString * phoneNumber;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) LocationCategory *locationCategory;

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class PointOfInterest;

@interface LocationCategory : NSManagedObject

@property (nonatomic, retain) id categoryColor;
@property (nonatomic, retain) NSString * categoryName;
@property (nonatomic, retain) NSSet *pointOfInterest;
@end


How to aggregate news for an iOS app?


My first post btw :)

Where do I start if I want to write a news aggregator app for an iPhone/iPad? I am familiar with Java but not so much with Objective-C.

So my question(s):

-how do I add RSS and Media RSS (MRSS) to the code in the first place?

-how do I store downloaded news (including media, videos and pics) so it is accessible without wifi/4g once dowloaded? Caching?

-is it legal to aggregate news content from other sources?

-does someone have any links that include some actual coding?

I know how to add RSS in HTML5 but I need help with Objective-c...

Any help and/or links on this subject is much appreciated.

Excelsior!


iOS - Swapping View Controller's in a Container View and persisting the data


I have a container view that swaps to child view controllers. Upon swapping the view controllers though I lose the data the controller had when it is deallocated from memory.

How can I swap the child view controllers and keep the data the same way that a tab bar controller swaps them without losing deallocating data from memory?


UITableViewHeaderFooterView can't change background color to clearColor


This is my TableHeaderView class, that extends UITableViewHeaderFooterView. This class does not have a Nib file and everything is done programmatically.

I want its background color to be transparent, but I cannot make it work. I've tried setting [self.backgroundView setBackgroundColor:[UIColor clearColor]], [self setBackgroundView:nil], [self.contentView setBackgroundColor:[UIColor clearColor]], but the final result is always a black background.

I've already spent hours on this, and I really have no idea how to fix this. What do I need to do to get this working?

#import "TableHeaderView.h"

@interface TableHeaderView ()

@property (strong, nonatomic) UIView *background;
@property (strong, nonatomic) UILabel *text;

@end

@implementation TableHeaderView

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
  self = [super initWithReuseIdentifier:reuseIdentifier];

  if (self.contentView) {
    self.background = [UIView new];
    [self.background setBackgroundColor:[UIColor colorWithWhite:0.0f alpha:0.5f]];
    [self.background setTranslatesAutoresizingMaskIntoConstraints:NO];

    self.text = [UILabel new];
    [self.text setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.text setText:@"Label"];
    [self.text setFont:[UIFont fontWithName:@"HelveticaNeue" size:15.0f]];
    [self.text setTextColor:[UIColor whiteColor]];
    [self.text setBackgroundColor:[UIColor redColor]];

    [self.background addSubview:self.text];
    [self.contentView addSubview:self.background];

    [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [self.background addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[L]-10-|"
                                                                            options:0
                                                                            metrics:nil
                                                                              views:@{@"L": self.text}]];

    [self.background addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[L]|"
                                                                            options:0
                                                                            metrics:nil
                                                                              views:@{@"L": self.text}]];

    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[V]-10-|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:@{@"V": self.background}]];

    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[V]|"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:@{@"V": self.background}]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:@{@"contentView" : self.contentView}]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:@{@"contentView" : self.contentView}]];

    [self setBackgroundView:[UIView new]];                          // I can't change this background color to
    [self.backgroundView setBackgroundColor:[UIColor whiteColor]];  // be transparent. It gets black instead.
  }

  return self;
}

@end


Objective-C: Why is my object being instantiated as __NSMallocBlock__?


I am running into a strange problem where I am trying to dynamically create a new instance of a Class property (arrayClass) that I have set and stored previously:

NSObject *instance = [[self.arrayClass alloc] init];
if ( ![instance isKindOfClass:self.arrayClass] )
    NSLog(@"Say what?!");

If I break and log self.arrayClass, it shows the proper class on the console (in this case, called Store), but when I attempt to create an instance of it dynamically and log the type of the instance, it is showing its class as __NSMallocBlock__.

What the heck is going on??


How to send data between View Controllers for iOS Programming? [duplicate]


This question already has an answer here:

I'm new to iOS programming and I have an app assignment for school. I'll briefly describe what I'm trying to do and what I have.

I have 2 container views. The one is the "bottom bar" of the game, and the other is the "content" of the game. Heres what it looks like in my storyboard:

enter image description here

The CenterViewController has an ImageView,4 buttons, and a label.

The BottomBarViewController has labels and a button. The label shows as "10" is a Countdown timer, and the button is at the far right of the container.

What I want to do:

I'm trying to control the CenterViewController for 2 scenarios:

1.) The 10 second timer hits 0

2.) The button is pressed before the time runs out

So basically once you hit Play, I want the CenterViewController to be displaying the image. Once the timer from the BottomBarViewController reaches 0 OR the Button is pressed, I want the Image from the CenterViewController to update to hidden and the Buttons behind it to be updated to visible.

I'm not sure how to go about implementing this. Some how the two view controllers need to have access to each others data, but I'm not sure how.


Objective C IRR calculation compared to Excel IRR function


The discussion below provides codes in Objective C IRR calculation that is consistently incorrect when compared to Excel IRR function. Does anyone know why there is such a difference?

The code used is offered in this previous discussion:

Calculate IRR (Internal Rate Return) and NPV programatically in Objective-C

The test cash flow I am using to calculate the IRR is the following: "Print tempCashFlow: ( "-5099701.25", "-22503.796875", "-22503.79296875", "-22503.79296875", "-20907.26171875", "-17899.7421875", "-17899.7421875", "-17899.7421875", "-14660.69140625", "-12447.80078125", "-12447.796875", "-12018.1640625", "-5991.81640625", "-5991.81640625", "-5991.81640625", "-2885.875", "1653.125", "1653.125", "1653.125", "8307.328125", "11110408.45703125" )

The above temporary cash flow contains quarterly figures over a 5-year period (i.e. 20 periods plus the time zero period... so 21 figures in the cash flow).

The code delivers 15.2% IRR instead of circa 16.0% produced by Excel IRR function. I also tested it manually, and I believe 16% is the correct answer. Can anyone help understand what may be wrong with the code? I cannot see any issues. It also appears to be identical to code promoted on this link as well:

http://ift.tt/1IXyoR7

PS: I've also noticed that the margin of error increases dramatically if I reduce the cash flow to a 2-year period instead of a 5-year period (e.g. something like 35% (incorrect) versus 45% IRR (correct answer)


Sorting NSArray of NSDictionary...not completely working


So I have NSMutableArray of NSDictionary items. Each NSDictionary item has a key "name" that should be used to sort the array alphabetically. Except its "sorting" partially works. Its not sorting in exact alphabetical order. It's moving some of the dictionary in order, but leaves some out of order.

NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}

I even tried this code

NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
/*[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];*/
section1 = [[NSArray arrayWithArray:section1] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]].mutableCopy;
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}


Import swift class into objective c storyboard


Im trying to integrate implement the project http://ift.tt/YXSBoY into my objective c project.

I have an objc bridging header that Xcode automatically made for me

I translated the ViewController.swift code as such

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Walkthrough" bundle:nil];
BWWalkthroughViewController *walkthrough = [sb instantiateViewControllerWithIdentifier:@"walk"];
BWWalkthroughPageViewController *page_zero = [sb instantiateViewControllerWithIdentifier:@"walk0"];
BWWalkthroughPageViewController *page_one = [sb instantiateViewControllerWithIdentifier:@"walk1"];
BWWalkthroughPageViewController *page_two = [sb instantiateViewControllerWithIdentifier:@"walk2"];
BWWalkthroughPageViewController *page_three = [sb instantiateViewControllerWithIdentifier:@"walk3"];

walkthrough.delegate = self;
[walkthrough addViewController:page_zero];
[walkthrough addViewController:page_one];
[walkthrough addViewController:page_two];
[walkthrough addViewController:page_three];

[self presentViewController:walkthrough animated:YES completion:nil];

and I import the swift classes like so:

import "SkipTheLine-Swift.h"

My bridging header file's name is "SkipTheLine-Bridging-Header.h"

now, when I run the code, I get this

2015-04-25 16:47:46.740 SkipTheLine[1631:215786] Unknown class BWWalkthroughViewController in Interface Builder file. 2015-04-25 16:47:46.754 SkipTheLine[1631:215786] -[UIViewController setDelegate:]: unrecognized selector sent to instance 0x12651cf90 2015-04-25 16:47:46.755 SkipTheLine[1631:215786] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setDelegate:]: unrecognized selector sent to instance 0x12651cf90' * First throw call stack: (0x1838aa530 0x19482c0e4 0x1838b15f4 0x1838ae3ac 0x1837b2c4c 0x10009c494 0x1880eca14 0x1880d5d08 0x1880ec3b0 0x1880ec03c 0x1880e5590 0x1880b8e60 0x18835846c 0x1880b73d0 0x183862d34 0x183861fd8 0x183860088 0x18378d1f4 0x18cbb76fc 0x18811e10c 0x10009e174 0x194eaaa08) libc++abi.dylib: terminating with uncaught exception of type NSException

Any ideas as to how I can use the swift code in interface builder?


UITableView Navigation not working


I have the following hierarchy in my app but the navigation controller isn't working. When I go back up the hierarchy in the storyboard, the higher level tableview controllers are blank instead of showing the previous view.

UITabBarController
        UINavigationController
                UITableViewController
                UITableViewController
                DetailViewController

Here's my code for the TableView Controller

@interface ExerciseTableViewController ()

@end

@implementation ExerciseTableViewController


- (void)viewDidLoad {

    UIBarButtonItem *add = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addExercise:)];
    self.navigationItem.rightBarButtonItem = add;

    NSLog(@"level: %i, currentSMID: %i, currentMID: %i", _level, _currentSMID, _currentMID);

    if (self.managedObjectContext_ == nil) {
        self.managedObjectContext_ = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    if (_level == 1) {
        _submuscleNameArray = [self submuscleGroup:_currentMID valueForKeyPath:@"submuscleGroup"];
        _submuscleIDArray = [self submuscleGroup:_currentMID valueForKeyPath:@"submuscleID"];
    } else if (_level == 2) {
        //loading and sorting exercise list
        _exerciseList = [self loadExercise:_currentMID sub:_currentSMID];
        _exerciseListSorted = [self sortKeysByName];
    } else {
        [self loadMuscleGroup];
    }

    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger count;

    if (_level == 0) {
        count = [_muscleNameArray count];
    } else if (_level == 1) {
        count = [_submuscleNameArray count];
    } else {
        count = [_exerciseList count];
    }

    return count;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_level == 0) {
        int muscleID = [_muscleIDArray[indexPath.row] intValue];
        NSLog(@"MuscleID: %i", muscleID);
        NSArray *submuscleArray = [self submuscleGroup:muscleID valueForKeyPath:@"submuscleID"];
        if (submuscleArray == nil || [submuscleArray count] == 0) {

            _currentMID = muscleID;
            _level = 2;
            _detailTitle = _muscleNameArray[indexPath.row];
                    NSLog(@"title: %@", _detailTitle);
            [self performSegueWithIdentifier:@"drillDown2" sender:self];
        } else {
            _currentMID = muscleID;
            _level = 1;
            _detailTitle = _muscleNameArray[indexPath.row];
                    NSLog(@"title: %@", _detailTitle);
        [self performSegueWithIdentifier:@"drillDown" sender:self];
        }

    } else if (_level == 1) {

        _level = 2;
        _currentSMID = [_submuscleIDArray[indexPath.row] intValue];
        _detailTitle = _submuscleNameArray[indexPath.row];
        [self performSegueWithIdentifier:@"drillDown2" sender:self];

    } else {
        _detailTitle = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:0];
        _equipment = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:1];
        _image = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:2];
        _imageNumber =  [[[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:3] intValue];
        _levelString = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:4];
        _status = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:5];
        _thumbnail = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:6];
        _type = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:7];
        _unitOfMeasure = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:8];
        _video = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:9];
        _workoutDirections = [[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:10];
        _exerciseID = [[_exerciseListSorted objectAtIndex:indexPath.row] intValue];

        [self performSegueWithIdentifier:@"showExerciseDetail" sender:self];

    }


}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"drillDownCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if (_level == 0) {
        [[cell textLabel] setText:[_muscleNameArray objectAtIndex:indexPath.row]];
    } else if (_level == 1) {
        [[cell textLabel] setText:[_submuscleNameArray objectAtIndex:indexPath.row]];
    } else {
        [[cell textLabel] setText:[[_exerciseList valueForKey:[_exerciseListSorted objectAtIndex:indexPath.row]] objectAtIndex:0]];
    }

    return cell;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return nil;
}


#pragma mark - 
#pragma Data Retrieval methods

-(NSArray *) sortKeysByName{

    //Method of NSDictionary class which sorts the keys using the logic given by the comparator block
    NSArray * sortArray = [_exerciseList keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

        //We do case insensitive comparision of two strings as we are not really concerned about
        //the "content" of the strings (please see sortKeysOnTheBasisOfNationalIncome method where
        //we would like to do the comparision with numeric search as an extra option)
        NSComparisonResult result = [[obj1 objectAtIndex:0] caseInsensitiveCompare:[obj2 objectAtIndex:0]];
        return result;
    }];

    //Show Result in the Output Panel
    for (int i = 0; i < [sortArray count]; i++) {
        NSLog(@"WorkoutID:%@, WorkoutName:%@",[sortArray objectAtIndex:i], [[_exerciseList valueForKey:[sortArray objectAtIndex:i]] objectAtIndex:0]);
    }

    return sortArray;
}

- (void)loadMuscleGroup{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //this is needed because QuizViewController isn't the first level view. The managedObjectContext was nil before this declaration
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Muscle_Group"
                                              inManagedObjectContext:_managedObjectContext_];
    [request setEntity:entity];
    NSError *error;
    _muscleArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *muscleSort = [[NSSortDescriptor alloc] initWithKey:@"muscleGroup" ascending:YES];
    [_muscleArray sortUsingDescriptors:[NSMutableArray arrayWithObject:muscleSort]];
    _muscleNameArray = [_muscleArray valueForKeyPath:@"muscleGroup"];
    _muscleIDArray = [_muscleArray valueForKeyPath:@"muscleID"];
//    NSLog(@"muscleIDArray count:%i, muscleNameArray count:%i, muscleID1: %d, muscleID2: %d", [_muscleIDArray count], [_muscleNameArray count], _muscleIDArray[1], _muscleIDArray[2]);
}

- (NSArray *)submuscleGroup:(int)muscleID valueForKeyPath:(NSString *)string{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //this is needed because QuizViewController isn't the first level view. The managedObjectContext was nil before this declaration
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SubMuscle_Group"
                                              inManagedObjectContext:_managedObjectContext_];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"muscleID = %i", muscleID];
    NSLog(@"muscleID = %i", muscleID);
    [request setPredicate:predicate];
    [request setEntity:entity];
    NSError *error;
    NSMutableArray *submuscleArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *submuscleSort = [[NSSortDescriptor alloc] initWithKey:@"submuscleGroup" ascending:YES];
    [submuscleArray sortUsingDescriptors:[NSMutableArray arrayWithObject:submuscleSort]];
    NSArray *submuscleGroupArray = [submuscleArray valueForKeyPath:string];
    return submuscleGroupArray;
}

- (NSMutableDictionary *)loadExercise:(int)muscleID sub:(int)subMuscleID{

    //Getting Array from Workout Muscle Relationship Table
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workout_Muscle_Relationship"
                                              inManagedObjectContext:_managedObjectContext_];
    NSPredicate *predicate;
    if (subMuscleID != 0) {
        predicate = [NSPredicate predicateWithFormat:@"muscleID = %i AND submuscleID = %i", muscleID, subMuscleID];
    } else {
        predicate = [NSPredicate predicateWithFormat:@"muscleID = %i", muscleID];
    }

    [request setPredicate:predicate];
    [request setEntity:entity];
    NSError *error;
    NSMutableArray *workoutRelationshipArray = [[_managedObjectContext_ executeFetchRequest:request error:&error] mutableCopy];
    NSSortDescriptor *workoutSort = [[NSSortDescriptor alloc] initWithKey:@"workoutID" ascending:YES];
    [workoutRelationshipArray sortUsingDescriptors:[NSMutableArray arrayWithObject:workoutSort]];
    NSArray *workoutIDArray = [workoutRelationshipArray valueForKeyPath:@"workoutID"];


    //Getting Array from Workout Group Table
    NSFetchRequest *request2 = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Workout_Group_Table"
                                               inManagedObjectContext:_managedObjectContext_];
    [request2 setEntity:entity2];
    NSMutableArray *workoutArray = [[_managedObjectContext_ executeFetchRequest:request2 error:&error] mutableCopy];
    NSSortDescriptor *workoutSort2 = [[NSSortDescriptor alloc] initWithKey:@"workoutID" ascending:YES];
    [workoutArray sortUsingDescriptors:[NSMutableArray arrayWithObject:workoutSort2]];
    NSArray *workoutIDArray2 = [workoutArray valueForKeyPath:@"workoutID"];
    NSArray *workoutName = [workoutArray valueForKeyPath:@"workoutName"];
    NSArray *equipmentArray = [workoutArray valueForKeyPath:@"equipment"];
    NSArray *imageArray = [workoutArray valueForKeyPath:@"image"];
    NSArray *imageNumberArray = [workoutArray valueForKeyPath:@"imageNumber"];
    NSArray *levelStringArray = [workoutArray valueForKeyPath:@"level"];
    NSArray *statusArray = [workoutArray valueForKeyPath:@"status"];
    NSArray *thumbnailArray = [workoutArray valueForKeyPath:@"thumbnail"];
    NSArray *typeArray = [workoutArray valueForKeyPath:@"type"];
    NSArray *unitOfMeasureArray = [workoutArray valueForKeyPath:@"unitOfMeasure"];
    NSArray *videoArray = [workoutArray valueForKeyPath:@"video"];
    NSArray *workoutDirectionsArray = [workoutArray valueForKeyPath:@"workoutDirections"];
    NSArray *workoutID = [workoutArray valueForKeyPath:@"workoutID"];
    NSArray *muscleImageArray = [workoutArray valueForKey:@"muscleImage"];

    NSMutableDictionary *list = [NSMutableDictionary new];

    NSLog(@"workoutIDArray count: %i, workoutIDArray2 count: %i", [workoutIDArray count], [workoutIDArray2 count]);
    int start = 0;

    for (int i = 0; i < [workoutIDArray count]; i ++) {
        NSLog(@"i:%i", i);
        for (int j = start; j < [workoutIDArray2 count]; j++) {
            NSLog(@"j:%i",j);
            if (workoutIDArray[i] == workoutIDArray2[j]) {
                NSArray *temp = [NSArray arrayWithObjects:workoutName[j], equipmentArray[j], imageArray[j], imageNumberArray[j], levelStringArray[j], statusArray[j], thumbnailArray[j], typeArray[j], unitOfMeasureArray[j], videoArray[j], workoutDirectionsArray[j], workoutID[j], muscleImageArray[j], nil];
                NSString *temp2 = [[NSString alloc] initWithFormat:@"%@", workoutIDArray2[j]];
                [list setValue:temp forKey:temp2];
                start = j;
                break;
            }
        }
    }



    return list;

}

- (NSString *)getExerciseInfo:(int)eid valueForKeyPah:(NSString *)string{
    NSString *result;



    return result;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{


    if ([segue.identifier isEqualToString:@"showExerciseDetail"]) {
        //ExerciseDetail *exerciseDetail = (ExerciseDetail *)segue.destinationViewController;
        //exerciseDetail.pageTitle = detailTitle;
        //UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        ExerciseDetail *exerciseDetail = (ExerciseDetail *)segue.destinationViewController;
        exerciseDetail.title = _detailTitle;
        exerciseDetail.exerciseID = _exerciseID;
        exerciseDetail.imageNumber = _imageNumber;
        exerciseDetail.image = _image;
        exerciseDetail.equipment = _equipment;
        exerciseDetail.levelString = _levelString;
        exerciseDetail.status = _status;
        exerciseDetail.thumbnail = _thumbnail;
        exerciseDetail.type = _type;
        exerciseDetail.unitOfMeasure = _unitOfMeasure;
        exerciseDetail.video = _video;
        exerciseDetail.workoutDirections = _workoutDirections;
    } else if ([segue.identifier isEqualToString:@"drillDown"] || [segue.identifier isEqualToString:@"drillDown2"]){
        //UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        ExerciseTableViewController *tableView = segue.destinationViewController;
        tableView.title = _detailTitle;
        NSLog(@"title: %@", _detailTitle);
        tableView.delegate = self;
        tableView.level = _level;
        tableView.currentSMID = _currentSMID;
        tableView.currentMID = _currentMID;
        tableView.muscleNameArray = _muscleNameArray;
        if (_level == 2) {
            tableView.submuscleNameArray = _submuscleNameArray;
        }
        NSLog(@"level: %i, currentSMID: %i, currentMID: %i", _level, _currentSMID, _currentMID);
    } else if ([segue.identifier isEqualToString:@"addExercise"]){
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        AddExerciseViewController *addExercise = (AddExerciseViewController *)navController.topViewController;
        addExercise.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;    
    } else if ([segue.identifier isEqualToString:@"dismissView"]){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)addExercise:(id)sender {
    [self performSegueWithIdentifier:@"addExercise" sender:sender];
}

- (void)viewDidAppear:(BOOL)animated{
    NSLog(@"muscleNameArray count: %i, submuscleNameArray count: %i, exercistList count: %i", [_muscleNameArray count], [_submuscleNameArray count], [_exerciseList count]);
    [super viewDidAppear:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [self.myWorkoutList reloadData];
    NSLog(@"muscleNameArray count: %i, submuscleNameArray count: %i, exercistList count: %i", [_muscleNameArray count], [_submuscleNameArray count], [_exerciseList count]);
    [super viewWillAppear:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


Why some Cocoa Touch APIs use this method declaration


Almost all Cocoa Touch APIs use this method defination and i just wonder why used like this instead of other notations?

NSString *trimString(BOOL useComma) {
    ...
    return @"";
}

Thanks to above method declaration I'll use like this without self sign;

trimString(YES)

So i really wonder why all APIs use this notation. Thank you!


Converting seconds to mm:ss returns (null)


I'm trying to change seconds to mm:ss. I'm retrieving the seconds from a json file, it returns fine but once I try to convert it to mm:ss, it just returns (null)

NSDictionary *content = [video valueForKeyPath:@"media$group.yt$duration"];
NSString *thetimehere = [content valueForKeyPath:@"seconds"];


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];    
[dateFormat setDateFormat:@"mm:ss"];

NSDate *dte = [dateFormat dateFromString:thetimehere];
cell.videolength.text = [NSString stringWithFormat:@"%@",dte ];
NSLog(@"Times: %@", dte);

What could be the response for the null response?!


UIViewController Destructor not being called


Currently I have two UIViewControllers called FormA and FormB

Now FormA calls FormB as such (formB property in formA is nonatomic and strong)

self.formB = [[ MediaPlayer alloc] initWithNibName:@"MediaPlayer" bundle:nil ];

[self presentViewController:self.formB animated:TRUE completion:nil];

and when FormB attempts to close it goes back to FormA as such

[ ((FormA*)self.presentingViewController) BackHere];

Now Back in FormA. FormA attempts to close FormB in this way

[self.presentedViewController dismissViewControllerAnimated:TRUE completion:nil];

self.formB = nil;

Doing the above does not call the destructor in FormB which is

-(void)dealloc {

    /* Desructor*/
}

Why si the destructor not being called ?


How can I rezise a subview inside of an UIScrollView?


My app is built like this (i cannot post images)

UIViewController  
|  
|----UIView  
     |  
     |----UIScrollView   
          |  
          |----UIView (here are added my buttons, called contentView)

I would like to add buttons dinamically, depending on WebService response. I add these buttons programatically and it goes well, but the views lack space. To acomplish that goal, I have to resize the view in order to show correectly these new icons, but I cannot get the desired effect. What should I do to do this? Please, pardon my poor English xD.

== EDIT ==

Here is the code where I am adding some UISwitch to the contentView

  1. UISwitch *switchDebito=[[UISwitch alloc] initWithFrame:CGRectMake(260, 1080+(cantidadNotificacionesEnconrtadas * 35), 50, 35)];
  2. [switchDebito setOn:notification.NotificationDebit];
  3. [self.contentView addSubview:switchCredito];

In line 1 I create the switch, increasing its height eventually (not really important) Line 2 is pointless Line 3: here we add the switch to the contentView


How to initialize main window objects from custom class during program start?


I have a main window with a couple of popupbuttons. I want to clear them, then load the lists from a method in a custom class. I've got my view controller working and I know the method in the custom class (newRequest) is working because I added a NSLog command to print "Test" when the method executes. In AppDelegate I'm calling the method via: [polyAppRequest newRequest];. As I said, I know the method is executing. Why can't I removeallitems from the popupbutton from this custom class method? Thanks Keith


parse.com. take names by filters objective c


http://ift.tt/1HEaew0

I have 3 strings for Filters and need to receive a name of a lens by using this filters.

 PFQuery *query = [PFQuery queryWithClassName:@"lences"];
    [query whereKey:@"brand" equalTo:_brandString];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error){
        NSLog(@"%@", objects);

I make a code for 1 filter "brand" and need to add another 2 (type and aperture) to receive a names of lances


iOS animation flip book cover and ease up


I have a scroll view, and few buttons/images there. on clicking I would like such animation :

(image opens like )book cover opens, and related view controller opens with ease in animation and gets full screen.

Any thoughts ?

Something similar happening in cook app Link of cook app : http://ift.tt/1hiQ9yL

Edit : I have added animation, gif will run uninterrupted once completely loaded.

enter image description here


Self sizing cell just doesn't work for me


I tried to follow the WWCD 2014 session 226, which introduced the way to realize self sizing cells in iOS 8 using auto layout, and it just doesn't work as it should.


HHTableViewCell.h

#import <UIKit/UIKit.h>
@interface HHTableViewCell : UITableViewCell
@property (strong, nonatomic)UILabel *title;

@end



HHTableViewCell.m

#import "HHTableViewCell.h"

@implementation HHTableViewCell

@synthesize title = _title;

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // configure control(s)

#pragma mark -- title Lable
        _title = [[UILabel alloc] initWithFrame:CGRectInset(self.bounds, 15.0, 0.0)];
        _title.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
        _title.numberOfLines = 0;
        [self.contentView addSubview:_title];


#pragma mark -- constraints
        NSMutableArray *constraints = [[NSMutableArray alloc]init];
        UIView *contentView = self.contentView;

        [constraints addObject:[NSLayoutConstraint
                                constraintWithItem:_title
                                attribute:NSLayoutAttributeFirstBaseline
                                relatedBy:NSLayoutRelationEqual
                                toItem:contentView
                                attribute:NSLayoutAttributeTop
                                multiplier:1.8
                                constant:3.0]];

        [constraints addObject:[NSLayoutConstraint
                                constraintWithItem:_title
                                attribute:NSLayoutAttributeFirstBaseline
                                relatedBy:NSLayoutRelationEqual
                                toItem:contentView
                                attribute:NSLayoutAttributeTop
                                multiplier:1.8
                                constant:3.0]];

        [constraints addObject:[NSLayoutConstraint
                                constraintWithItem:_title
                                attribute:NSLayoutAttributeFirstBaseline
                                relatedBy:NSLayoutRelationEqual
                                toItem:contentView
                                attribute:NSLayoutAttributeTop
                                multiplier:1.8
                                constant:3.0]];

        [constraints addObject:[NSLayoutConstraint
                                constraintWithItem:contentView
                                attribute:NSLayoutAttributeHeight
                                relatedBy:NSLayoutRelationGreaterThanOrEqual
                                toItem:nil
                                attribute:0
                                multiplier:1.0
                                constant:44.0]];

        [constraints addObjectsFromArray:[NSLayoutConstraint
                                          constraintsWithVisualFormat:@"H:|-15-[_title]-15-|"
                                          options:0
                                          metrics:nil
                                          views:NSDictionaryOfVariableBindings(_title)]];



        [self.contentView addConstraints:constraints];
    }
    return self;

}

@end



MMTableViewController.h

#import <UIKit/UIKit.h>

@interface MMTableViewController : UITableViewController

@end



MMTableViewController.m

#import "MMTableViewController.h"
#import "HHTableViewCell.h"

@interface MMTableViewController ()

@end

@implementation MMTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerClass:[HHTableViewCell class] forCellReuseIdentifier:@"HiCell"];
    [self.tableView registerClass:[HHTableViewCell class] forCellReuseIdentifier:@"HCell"];

    self.tableView.estimatedRowHeight = 44.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 10;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"HiCell";

    HHTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.title.text = @"Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. Hello Apple. ";

    // Configure the cell...
    NSLog(cell.title.text);

    return cell;
}


@end


The cell is of fixed height and wrapping two lines of text. Looks like this:

Hello Apple. Hello Apple. Hello Apple. Hello
Aplle. Hello Apple. Hello Apple. Hello Apple...


Constraints and subviews are added programatically. Simulator is running iOS 8.3 in Xcode 6.3.1.


WatchKit call webview


I'm currently working on a Apple Watch app and I'm facing a problem. Since the app company I'm working on doesn't have a API, and is not planning to make, I use a UIWebView to parse some HTML into the app.

I'm trying to port this to the Apple Watch, but I cannot open a UIWebView in background using the handleWatchKitExtensionRequest delegate.

Is there any way to run a UIWebView background task and send some data from it to the Apple Watch app?


What is the best way to add a table view controller to a custom table view object? (using nib)


Im working with nib files, and one of my nib files is a custom view that represent a setting pop-up view for the app.

The nib looks like this:

enter image description here

Now, I want to create a controller class only for that UITableView component, a class to include all the setup methods for table view (like cellForRowAtIndexPath).

How do I do this?

Because if create a uitableviewcontroller class I cannot assign it to the table view component because it's of type uitableview, and if I create a uitableview objective c class so I dont get auto complete for those methods I need so something feels wrong here..

What is the proper way?

Thanks!!


physics body not inline with shape?


for some reason when i apply a physics body around the skshapenode it places the physics body more to the left and downwards of the actual shape even though the parameters of the physics body comes from the shape. does anyone know why? thanks.

-(SKShapeNode*) createGround1
{
    //create a rectangle
    ground1 = [SKShapeNode shapeNodeWithRect:CGRectMake(0, 0, 300, 19)];
    ground1.position = CGPointMake(800, 500);

    //applies physics to rectangle
    ground1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: CGSizeMake(ground1.frame.size.width, ground1.frame.size.height)];
    ground1.physicsBody.allowsRotation = false;
    ground1.physicsBody.dynamic = false;
    ground1.physicsBody.restitution = 0.0;

    return ground1;
}


NSString wordwrapping like UILabel NSLineBreakByWordWrapping


I want a wordwrapping for string to just wanted for the dynamic height calculations purpose, because in UILabel NSLineBreakByWordWrapping, counting string height for dynamic purpose is easy to adjust UILabel height please can any buddy let me know the wordwrapping in string ?

CGSize size = CGSizeZero;
NSString *carNameString = cars.name;
carNameString = [carNameString stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\n"];

CGRect f1 = [carNameString boundingRectWithSize:CGSizeMake([[UIScreen mainScreen]bounds].size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:[UIFont fontWithName:@"Copperplate" size:20] } context:nil];
size = CGSizeMake(f1.size.width, f1.size.height + 1);

Note: I am using iOS Version 6.3


Compose UIBarButtonItem changes position slightly when coming into view


When presenting a new view with a UIBarButtonSystemItemCompose button in the navigation bar, the position is slightly off and adjusts after the view has come into view.

Compose button changes position slightly when coming into view

I think this is a bug in iOS (version 8.3 used). It only happens when using the UIBarButtonSystemItemCompose. It does not happen with other types of Buttons (system, text or custom).

The only code needed to replicate this bug is to use this ViewController code with the view that will come into view:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UIBarButtonItem* composeBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
                                      target:nil
                                      action:nil];

    [self.navigationItem setRightBarButtonItem:composeBarButtonItem animated:YES];
}

@end

I have created a repository on GitHub with bare minimum code to reproduce the problem: http://ift.tt/1JaNgyy

Looks related to this: UIBarButtonItems shift position when UINavigationController is presented modally, except my bug only appears when using the UIBarButtonSystemItemCompose.

Any ideas?


iOS 8 push notification action buttons - code in handleActionWithIdentifier does not always run when app is in background


I am adding two action buttons to my push notifications on iOS 8: an Accept button and a Deny button. Neither button will open the app, but different server requests will be made depending on which button is pressed. Here's my setup:

+ (void)requestForPushNotificationToken {
    UIApplication *application = [UIApplication sharedApplication];
    // if ios 8 or greater
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
        [acceptAction setActivationMode:UIUserNotificationActivationModeBackground];
        [acceptAction setTitle:@"Accept"];
        [acceptAction setIdentifier:@"ACCEPT_ACTION"];
        [acceptAction setDestructive:NO];
        [acceptAction setAuthenticationRequired:NO];

        UIMutableUserNotificationAction *denyAction = [[UIMutableUserNotificationAction alloc] init];
        [denyAction setActivationMode:UIUserNotificationActivationModeBackground];
        [denyAction setTitle:@"Deny"];
        [denyAction setIdentifier:@"DENY_ACTION"];
        [denyAction setDestructive:NO];
        [denyAction setAuthenticationRequired:NO];

        UIMutableUserNotificationCategory *actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:@"ACTIONABLE"];
        [actionCategory setActions:@[acceptAction, denyAction]
                        forContext:UIUserNotificationActionContextDefault];

        NSSet *categories = [NSSet setWithObject:actionCategory];

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:categories];
        [application registerUserNotificationSettings:settings];
    } else if ([application respondsToSelector:@selector(registerForRemoteNotificationTypes:)]) { // ios 7 or lesser
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
    }
}

Then, in my delegate method, I am specifying actions to be taken when user pressed one of the action buttons:

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
    if ([identifier isEqualToString:@"ACCEPT_ACTION"]) {
        // Sending a request to the server here
    }
    else if ([identifier isEqualToString:@"DENY_ACTION"]) {
        // Sending a request to the server here
    }

    if (completionHandler) {
        completionHandler();
    }
}

The ideal scenario is that the user does not need to launch the app in the whole process; pressing Accept or Deny will make different calls to the server. With the code above, I am seeing very unstable behaviors with the button actions:

  • A lot of times, the code in the action handler doesn't execute when app is in background and no server calls are made at all; when this happens, if I tap on my app icon and launch my app, the handler code will immediately be run upon launching the app.
  • Occasionally, the handler code gets triggered and everything works fine. Server requests are made as soon as I press one of the action buttons.
  • If I put breakpoints in my Xcode and step through the handler code, the success rate is also 100%. I do not need to launch my app, and handler code gets executed when button is pressed.

Could anyone please help me figure out what's causing such unstable behavior? Thanks in advance.


Shared iAd on Tabbed Application


New to iOS development and I have a tabbed app with 4 tabs. I have an iAd showing on one tab and I don't want to regurgetate the code on every view controller and I know this is not the correct way to implement anyway. I have looked at the Apple code here and I'm struggling to be honest.

http://ift.tt/1hw3yBt

I have included the BannerViewController.m and BannerViewController.h in my application but I'm not fully sure how to get it to run the ad on each view controller.

Yours confused

JKX


Show directions on map with audio instructions - iOS


I want to use map view to instruct the route directions with audio instructions. I have implemented plotting route between two addresses. Answers are welcome but any suggestions will help me a lot.


Do multi-dimensional arrays eat memory and how do I free up their memory


I have a complex tableview. Objective C

To populate a number of labels in each cell I had a multi-dimension table composed of 2 NSMutableArrays (1 embedded inside the other). The result was an array that had 3 columns per row.

To free up memory I used [arrayname removeAllObjects];

Well all I can say is that this did absolutely nothing.

This array (which per row was only holding about 130 chars of data and in this sample data I only had 30 rows) was like a virus that's favourite food was memory. It ate chunks of 50mg like there was no tomorrow.

The removeAllObjects did nothing to recover memory.

I have searched high and low and find no clear way to free up memory when you are working with NSMutableArrays and it seems like multi-dimensional ones are cookie monsters.

In the end I removed the multi-dimensional array and just built a single NSMutableArray which was just all of the data concatenated into a string, which I then subStringed out the 3 pieces of data when I needed them.

Memory returned back to normal.

This may not have been the ideal solution. Has anyone found a clear way of releasing the memory of NSMutableArrays ?


Add missing years and corresponding values into arrays


I've been messing around with the JBChartView library and it seems really good for charting. It's easy enough to use but i'm having some problems getting my data in a format that i need for a particular chart.

The user can enter a value and corresponding year. This is saved using core data. The data could look like as follows:

Year: 0 Value: 100 Year:2 Value 200 Year 3 Value 150

I would create 2 arrays, 1 for the year number and another for the value. in this case though, I would get 3 bars. What i'd like is a bar with value 0 for Year 1.

I think the best way to approach this would be to look through the Year array, check to see if the first value is 0, then check if every consecutive year value is +1. If not, add 1 to the previous year and insert a value of 0 into the values array at the same index position.

I would like to know if this is the best approach and if I could get some help doing the comparison.

Thanks


Getting correct frame after setting constraint


I have a method that creates a mask layer based on the current frame of my UIImageView, which works as I expected. However, in one case, I modify the height constraint of a UIImageView in the viewWillAppear method, and then apply the mask creator to the UIImageView, which creates a mask with a worng size. So my question is, how can I force to get the modified correct frame of that UIImageView?

Right now I'm getting the height 140 insted of 105, but if I use layoutIfNeeded after setting the constraint it become 118, which is closer, but still not 105.

Updated:

The method that I use for creating the mask:

public func setupMaskForImageView() {
    let mask = CALayer()
    let resizedMaskImage = resizeImage(UIImage(named: imageMaskName)!, newSize: frame.size)
    mask.contents = resizedMaskImage
    mask.frame = CGRectMake(0, 0, frame.size.width, frame.size.height)
    layer.mask = mask
    layer.masksToBounds = true
}

and I modified the constraint in viewWillAppear with

imageHeight.constant = UIScreen.mainScreen().bounds.width / 2.5


Displaying two sets of results in one TableViewController


I know this is a startlingly stupid question, but I can't figure it out. Every answer involves a UISearchBar, which is not what I've got.

I'm trying to display 2 sets of results on one TableViewController.

Results to display

1) everything in my managedObjectContext which is set up in my viewDidLoad

2) a filtered set of results if a predicate is selected.

On MyTableViewController, I have a popover which instantiates when I click a UIBarButtonItem on MyTableViewController. On the popover, I set a predicate on MyTableViewController.

Basically, I'd like to toggle what's displayed and that display toggle is driven by whether my variable is nil (everything displays) or filtered (variable sets a predicate).


Must call a designated initializer of the superclass 'UIViewController' in Swift 1.2


I have the following init method which worked perfect before Swift 1.2.

init(items: NSArray, views: NSArray, showPageControl: Bool, navBarBackground: UIColor){
  super.init()

In Swift 1.2 the line with super.init() raises the error:

Must call a designated initializer of the superclass 'UIViewController'

The problem is that I have only two possible super init methods to call the one is with a codec and the other is with a nib. Both of which I do not have access to in this init method.

See the full class here the line of the error is this.

How can I correct the init method to make it work with Swift 1.2?

class SLPagingViewSwift: UIViewController, UIScrollViewDelegate {

  init(items: NSArray, views: NSArray, showPageControl: Bool, navBarBackground: UIColor){
        super.init()
        needToShowPageControl             = showPageControl
        navigationBarView.backgroundColor = navBarBackground
        isUserInteraction                 = true
        var i: Int                        = 0
        for item in items{
            if item.isKindOfClass(UIView.classForCoder()){
                var v             = item as UIView
                var vSize: CGSize = v.isKindOfClass(UILabel.classForCoder()) ? self.getLabelSize(v as UILabel) : v.frame.size
                var originX       = (self.SCREENSIZE.width/2.0 - vSize.width/2.0) + CGFloat(i * 100)
                v.frame           = CGRectMake(originX, 8, vSize.width, vSize.height)
                v.tag             = i
                var tap           = UITapGestureRecognizer(target: self, action: "tapOnHeader:")
                v.addGestureRecognizer(tap)
                v.userInteractionEnabled = true
                self.navigationBarView.addSubview(v)
                self.navItems.addObject(v)
                i++
            }
        }

        if (views.count > 0){
            var controllerKeys = NSMutableArray()
            i = 0
            for controller in views{
                if controller.isKindOfClass(UIView.classForCoder()){
                    var ctr = controller as UIView
                    ctr.tag = i
                    controllerKeys.addObject(NSNumber(integer: i))
                }
                else if controller.isKindOfClass(UIViewController.classForCoder()){
                    var ctr      = controller as UIViewController
                    ctr.view.tag = i
                    controllerKeys.addObject(NSNumber(integer: i))
                }
                i++
            }

            if controllerKeys.count == views.count {
               self.viewControllers = NSDictionary(objects: views, forKeys: controllerKeys)
            }
            else{
                var exc = NSException(name: "View Controllers error", reason: "Some objects in viewControllers are not kind of UIViewController!", userInfo: nil)
                exc.raise()
            }
        }
    }

}

Full Code


TextField not being added to ScrollView


When I input the following code, the textfields I added are not being displayed in the scrollview:

.h

@interface FirstViewController : UIViewController <UIScrollViewDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) UITextField *firstField;
@property (strong, nonatomic) UITextField *secondField;
@property (strong, nonatomic) UITextField *thirdField;

.m (viewDidLoad)

self.firstField.placeholder = @"First";
self.firstField.textAlignment = NSTextAlignmentCenter;
self.firstField.font = [UIFont fontWithName:@"Helvetica Neue Light" size:50.0];

self.secondField.placeholder = @"Second";
self.secondField.textAlignment = NSTextAlignmentCenter;
self.secondField.font = [UIFont fontWithName:@"Helvetica Neue Light" size:50.0];

self.thirdField.placeholder = @"Third";
self.thirdField.textAlignment = NSTextAlignmentCenter;
self.thirdField.font = [UIFont fontWithName:@"Helvetica Neue Light" size:50.0];

[self.scrollView addSubview:self.firstField];
[self.firstField autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeRight];
[self.firstField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.firstField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];

[self.scrollView addSubview:self.secondField];
[self.secondField autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.firstField];
[self.secondField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.secondField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];

[self.scrollView addSubview:self.thirdField];
[self.thirdField autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.secondField];
[self.thirdField autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeLeft];
[self.thirdField autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.scrollView];
[self.thirdField autoMatchDimension:ALDimensionHeight toDimension:ALDimensionHeight ofView:self.scrollView];

self.automaticallyAdjustsScrollViewInsets = NO;

I have self.scrollView is within a scrollView by the way (in a pageviewcontroller). I am using PureLayout to position the text fields, and I'm pretty sure the way I did it is correct. Is there something I'm missing?


How to create an Xcode project that is not an app but is visible in other projects?


I want to create a project with a handful of categories that add useful functionality to UIKit. I want to keep this as a separate project so that it can be source-controlled separately (and eventually hosted on github, and downloadable as a dependency via cocoa pods...but let's skip this for now.)

But all the Xcode 6.1 project templates imply an app inside. When I select an empty project it complains about missing base SDK. But this cannot be set without a target present. It is quite confusing. I don't need a target. Do I? The project should be just a shell for a number of categories + a accompanying summary header file.

I want to be able to drag this project as a subproject to any other proper app project, import the summary header file and expose those categories to the main project.

Any advice?


UIKit Dynamic spring back slightly


How can this effect be achieved with UIDynamicAnimator?

Layout:

------[uiview]-------->-------|anchor point|---<---[edge]

Interaction:

  • User can drag object past anchor point but it will slide to anchor point.
  • User can swipe right to anchor point but if velocity is high, the object will move slightly past it and bounce back to anchor point.

Populating ViewBased table from data in 6 different NSMutable arrays


I have 6 different NSMutable arrays [(Arr(A); Arr(B); etc.] each of which represents data for one cell of a row in the table. The array is essentially the key representation. They are built in a prior classes, passed to the current class and have exactly the same number of string objects (63) in each. The table is essential a data representation of

Questions:

  1. Must I build a NSDictionary with 'keys' and 'objects'. How do I build thatDictionary. I have tried various methods stepping through a count loop with no success. I can to find a method for inserting objects for specific keys.

  2. Can I load the table directly from the various arrays without a ViewController. I have the table and id's laid out but I have not been able to add a ViewController to this class - I only have 'Files Owner'. If this is easiest how can I do that.

  3. If needed, how do I take elements of the 6 arrays in order as a comma delimited string in another array that becomes the input to a row of of the table and therefore parsed into the table.

No code to offer because all my attempts w/code have been unsuccessful.

NEED SOME SPECIFIC DIRECTION HERE.

.h

     //  ReportsOutput.h
        //  Stamp Collection
        //  Created by Terry Lengel on 4/20/15.
        //  Copyright (c) 2015 Terry Lengel. All rights reserved.

        #import <Cocoa/Cocoa.h>
        #import <Foundation/Foundation.h>
        #import "ReportsClass.h"

        @interface ReportsOutput : NSWindowController <NSMenuDelegate,NSTableViewDataSource,NSTableViewDelegate,NSApplicationDelegate>{


        // variable and outlet for the table

            IBOutlet NSTableView *rptTable;

        }

        // data element sources

        @property(nonatomic,strong) NSMutableArray *tblYrScott;
        @property(nonatomic,strong) NSMutableArray *tblYrExt;
        @property(nonatomic,strong) NSMutableArray *tblYrYear;
        @property(nonatomic,strong) NSMutableArray *tblYrType;
        @property(nonatomic,strong) NSMutableArray *tblYrPrice;
        @property(nonatomic,strong) NSMutableArray *tblYrDescription;

        // the Display data source array for the table

        @property(strong) NSMutableArray *rptData;

        #pragma mark - Method Declarations

        -(BOOL)conditionData;

        -(NSDictionary *)makeDictionaryRecord:(NSString*)scott withInfo:(NSString*)ext withInfo:(NSString*)year withInfo:(NSString*)type withInfo:(NSString*)price withInfo:(NSString*)Description;

        @end

    .m

        //  ReportsOutput.m
        //  Stamp Collection
        //  Created by Terry Lengel on 4/20/15.
        //  Copyright (c) 2015 Terry Lengel. All rights reserved.

        #import "ReportsOutput.h"
        #import "ReportsClass.h"

        @interface ReportsOutput ()

        @end

        @implementation ReportsOutput

        @synthesize tblYrScott;
        @synthesize tblYrExt;
        @synthesize tblYrType;
        @synthesize tblYrPrice;
        @synthesize tblYrYear;
        @synthesize tblYrDescription;

        @synthesize rptData;

        -(id)initWithWindow:(NSWindow *)window{
            self = [super initWithWindow:window];
            if (self){
                // initialize code here
            }
            return self;

        }


        -(void)windowDidLoad {
            [super windowDidLoad];

            // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        }

        -(void)applicationDidFinishLaunching:(NSNotification *)notification{

            //Insert code here to initialize your application
        }

        //  Terminate the app by using the RED button:

        -(BOOL)applicationShouldTerminateAfterLastWindowClosed:
        (NSApplication *)sender{

            return YES;

        }

        -(void)awakeFromNib{

            if (self.conditionData == YES){

                [rptTable reloadData];
            }

        }

        -(BOOL)windowShouldClose:(id)sender{
            return YES;
        }

        -(void)performClose:(id)sender{
            [self close];
        }

        #pragma mark - Table View Data Source

        -(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{

            return rptData.count;

        }

        -(NSView *) tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

            NSTableCellView *scott = [tableView makeViewWithIdentifier:@"Scott" owner:self];

            scott.textField.stringValue = [self.rptData objectAtIndex:row];

            return scott;


        }

        // request for sorting

        -(void) tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray *)oldDescriptors{

            // table view received sort request
            //sort the data, then reload the tableView data:

            [rptData sortUsingDescriptors:[rptTable sortDescriptors]];

            [rptTable reloadData];

        }

        -(BOOL)conditionData{

            BOOL conditionData = NO;

            NSString *rPrice;
            NSString *rExt;
            NSString *rYear;
            NSString *rType;
            NSString *rDescription;


            for (int b=0; b<[tblYrScott count]; ++b){

                //condition source data to remove any null appearences

                rExt = [tblYrExt objectAtIndex:b];
                if (rExt == (id)[NSNull null] || rExt.length == 0 ){
                    rExt = @"None";
                }else if ([rExt isEqualToString:@" "]){
                    rExt = @"None";
                }else
                    rExt = [tblYrExt objectAtIndex:b];

                rYear = [tblYrYear objectAtIndex:b];
                if (rYear == (id)[NSNull null] || rYear.length == 0 ){
                    rYear = @" ";
                }else
                    rYear = [tblYrYear objectAtIndex:b];

                rType = [tblYrType objectAtIndex:b];
                if (rType == (id)[NSNull null] || rType.length == 0 ){
                    rType = @" ";
                }else
                    rType = [tblYrType objectAtIndex:b];

                rPrice = [tblYrPrice objectAtIndex:b];
                if (rPrice == (id)[NSNull null] || rPrice.length == 0 ){
                    rPrice = @"n/r";
                }else
                    rPrice = [tblYrPrice objectAtIndex:b];

                rDescription = [tblYrDescription objectAtIndex:b];
                if (rDescription == (id)[NSNull null] || rDescription.length == 0 ){
                    rDescription = @" ";
                }else
                    rDescription = [tblYrDescription objectAtIndex:b];

                NSDictionary *rptData = @{@"Scott":[tblYrScott objectAtIndex:b],@"Ext":rExt,@"Year":rYear,@"Type":rType,@"Price":rPrice,@"Description":rDescription};

            }

            //[rptTable reloadData];

            return conditionData = YES;
        }


        -(NSDictionary*) makeDictionaryRecord:(NSString *)scott withInfo: (NSString *)ext withInfo: (NSString *)year withInfo: (NSString *)type withInfo: (NSString *)price withInfo: (NSString *)description{

            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:scott,@"Scott",ext,@"Ext",year,@"Year",type,@"Type",price,@"Price",description,@"Description", nil];

           return dict;

        }

        @end

Data Sample:

2015-04-25 12:20:49.251 StampsProjectDev[2981:591183]  rptData = {
    Description = "Lunar New Year - Horse";
    Ext = None;
    Price = "n/r";
    Scott = 4846;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Jimi Hendrix";
    Ext = None;
    Price = "n/r";
    Scott = 4880;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Charlton Heston";
    Ext = None;
    Price = "n/r";
    Scott = 4892;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Janice Joplin";
    Ext = None;
    Price = "n/r";
    Scott = 4916;
    Type = C;
    Year = 2014;
}
2015-04-25 12:20:49.252 StampsProjectDev[2981:591183]  rptData = {
    Description = "Ralph Ellison";
    Ext = None;
    Price = "n/r";
    Scott = 4866;
    Type = C;
    Year = 2014;
}


Parse PFFile download order iOS


I'm storing 5 PFFiles in an array and using getDataInBackgroundWithBlock to download those files from Parse.

The problem is the order at which they appear in the table view cells is different every time, presumably because the files are download at different speeds due to the different file sizes.

for (PFFile *imageFile in self.imageFiles) {
  [imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
      UIImage *avatar = [UIImage imageWithData:imageData];
      [self.avatars addObject:avatar];
      cell.userImageView.image = self.avatars[indexPath.row];
    }
  }];
}

The self.imageFiles array is in the correct order. How do I ensure that the images downloaded are added to the self.avatars array in the same order as the self.imageFiles?


character jumps more than anticipated?


my problem is that when i jump at the start of my game it jumps three times when I only want to jump 2 times. What the code does is at the start a bool startgame is set to false and when clicked start moving the shape and starts the animation of dan, the character of my game. In the update method whenever the shape and dan touch the isjumping boolean variable is set to false so that when you click, dan jumps and then sets the didjumponce boolean to true so that it can jump for a second time. but for some reason at the start of the game it allows dan to jump three times. i tried setting a touch counter(timestapped) to 0 and every time there is a tap it adds on 1 so that when it checks if you can jump a second time is doesn't allow it. but it still does. thanks :)

@implementation GameScene
bool isJumping;
bool isPlaying;
bool didJumpOnce;
bool startGame = false;
int timesTapped = 0;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    /* Called when a touch begins */

    timesTapped++;

    // checks to see if the game has started, if it hasn't, starts dan's animation
    if (startGame == false)
    {
        startGame = true;
        [self dansAnimation];
    }
    else if (isJumping == false)
    {
        isJumping = true;
        didJumpOnce = true;

        dan.physicsBody.velocity = CGVectorMake(0, 0);
        [dan.physicsBody applyImpulse: CGVectorMake(0, 55)];
    }
    else if (didJumpOnce == true && timesTapped != 2)
    {
       didJumpOnce = false;

        dan.physicsBody.velocity = CGVectorMake(0, 0);
        [dan.physicsBody applyImpulse: CGVectorMake(0, 55)];
    }
}

-(void)update:(CFTimeInterval)currentTime
{
    /* Called before each frame is rendered */

   if (startGame == true)
   {
        shape.position = CGPointMake(shape.position.x - 7, shape.position.y);
   }

   if (CGRectIntersectsRect(dan.frame, shape.frame))
   {
        isJumping = false;
   }
}
@end


How to stop a sprites physicsBody from moving?


In my SpriteKit game i move several sprites using [sprite.physicsBody applyImpulse:vector]; but at a specific point i the game i want them to stop. I already tried to apply the exact opposite impulse.. but that did not worked very well.

Thanks


Getting what is inside the object in a nsmutabledictionary


I put some breakpoints to see whats is happening, and I have an array that receives the object from a nsmutabledictionary, and it's "working", but not correctly my code is

for(int i=0; i < notificationsArray.count; i++){
    UILocalNotification *notification = [notificationsArray objectAtIndex:i];
    NSDictionary *userInfoCurrent = notification.userInfo;
    NSString *uid = [NSString stringWithFormat:@"%@", [userInfoCurrent valueForKey:@"key1"]];
    firstletter2 = [NSString stringWithFormat:@"%@", uid];




    [alfabeto addObject:firstletter2];

    while((i < notificationsArray.count) && ([firstletter2 isEqualToString:[NSString stringWithFormat:@"%@", _recebelembrete[i]]])){

        [_arrayforkey addObject:[notificationsArray objectAtIndex:i]];
        i++;

    }
    i--;

    //int x = [firstletter2 intValue];
    if([_dictionaryComplete valueForKey:firstletter2] !=nil){


        [_arrayforkey addObject:[_dictionaryComplete valueForKeyPath:firstletter2]];
    }

    [_dictionaryComplete setObject:_arrayforkey forKey:firstletter2];
    _arrayforkey = [[NSMutableArray alloc]init];

This is what appears if I put the breakpoints

arrayforkey __NSArrayM *    @"2 objects"    0x00007f88607223f0

[0] UIConcreteLocalNotification *   0x7f8860479940  0x00007f8860479940

[1] __NSArrayM *    @"1 object" 0x00007f8860483c10

[0] UIConcreteLocalNotification *   0x7f886046e6b0  0x00007f886046e6b0

I need to get the UIConcreteLocalNotification that in inside the _NSArrayM and put on the _arrayforkey.


Objective C - Remove only UIButtons from superview


I am fairly new to objective-c and I have ran into an issue that I have had a hard time solving..

I am using ShinobiDataGrid and using their prepareCellForDisplay.

To get text to display I would do this:

if([cell.coordinate.column.title isEqualToString:@"Task"]){
            textCell.textField.textAlignment = NSTextAlignmentLeft;
            textCell.textField.text = cellDataObj.task;
        }

but for a particular cell, I am trying to add a custom button:

if([cell.coordinate.column.title isEqualToString:@"selected"]){


            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 10 , 32, 32);



            if(cellDataObj.selected){

                [button setImage:[UIImage imageNamed:@"checked-box.png"] forState:UIControlStateNormal];

            }else{

                [button setImage:[UIImage imageNamed:@"unchecked-box.png"] forState:UIControlStateNormal];

            }

            button.tag = cell.coordinate.row.rowIndex;
            [button addTarget:self action:@selector(CheckBoxPressed:) forControlEvents:UIControlEventTouchUpInside];

            [cell addSubview:button];

            [button removeFromSuperview];

        }

and I first run the app, the checkbox appears. but when I reload my ShinobiDataGrid the checkbox appears again. I tried removing the button from the superview, but that didn't work...any suggestions ? When I reload my ShinobiDataGrid a 3rd time, the checkbox does not appear for a 3rd time, just adds another when I reload the ShinobiDataGrid the 2nd time. Here is the whole method:

- (void)shinobiDataGrid:(ShinobiDataGrid *)grid prepareCellForDisplay:(SDataGridCell *)cell
{

    SDataGridTextCell* textCell = (SDataGridTextCell*)cell;

    CellData *cellDataObj = [cellHolderDisplay objectAtIndex:cell.coordinate.row.rowIndex];

    textCell.textField.textAlignment = NSTextAlignmentCenter;

    if([cell.coordinate.column.title isEqualToString:@"selected"]){


        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 10 , 32, 32);



        if(cellDataObj.selected){

            [button setImage:[UIImage imageNamed:@"checked-box.png"] forState:UIControlStateNormal];

        }else{

            [button setImage:[UIImage imageNamed:@"unchecked-box.png"] forState:UIControlStateNormal];

        }

        button.tag = cell.coordinate.row.rowIndex;
        [button addTarget:self action:@selector(CheckBoxPressed:) forControlEvents:UIControlEventTouchUpInside];

        [cell addSubview:button];

        [button removeFromSuperview];

    }


    if([cell.coordinate.column.title isEqualToString:@"Task"]){
        textCell.textField.textAlignment = NSTextAlignmentLeft;
        textCell.textField.text = cellDataObj.task;
    }

    if([cell.coordinate.column.title isEqualToString:@"BLine. Start"]){
        textCell.textField.text = cellDataObj.baselineDate;
    }
}

Any suggestions ?

Here is the CheckBoxPressed method:

- (void)CheckBoxPressed:(UIButton *)sender
{
    CellData *cell = [cellHolder objectAtIndex:sender.tag];

    if([cell selected] == YES)
    {
        [[cell actualDate]setString:@""];
        [[cell finishedDate] setString:@""];
        [cell setSelected:NO];
    }
    else
    {
        if(([[cell actualDate] isEqualToString:@""]) && ([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell actualDate]setString:[NSString stringWithFormat:@"%@ 8:00:00 AM",[self SetSpecialDateFormat:[NSDate date]]]];
            [[cell finishedDate]setString:[NSString stringWithFormat:@"%@ 4:00:00 PM",[self SetSpecialDateFormat:[NSDate date]]]];
        }
        //actual date not populated but finish date populated
        else if(([[cell actualDate]isEqualToString:@""]) && !([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell actualDate]setString:[cell finishedDate]];
        }
        //finish date not populated but actual date populated
        else if(!([[cell actualDate] isEqualToString:@""]) && ([[cell finishedDate] isEqualToString:@""]))
        {
            [[cell finishedDate]setString:[cell actualDate]];
        }

        [cell setSelected:YES];

    }
    [self UpdateEdittedCells:cell];
    [self SetDisplayHolder];

    //refresh grid
    [gridReference reload];
}


What's causing this memory leak?


The Problem

I'm currently building an iPad game using SpriteKit. The gameplay is driven by sound provided by EZAudio. After running the Instrumentation tools to profile my app, I noticed that whenever the GameViewController is shown memory allocation jumps up. When I repeatedly show the screen (5+ times) it crashes the app. My project uses ARC.

Navigation

The navigation consists of 4 ViewControllers:

  1. MenuViewController: This shows the menu
  2. CharacterSelectionViewController: It lets you a pick a character to use
  3. GameViewController: This lets you play a game with the player chosen
  4. ScoreViewController: It shows you the score you achieved in the game

1 - MenuViewController

From here you can navigate to CharacterSelectionViewController via a Show (e.g. Push) segue.

2 - CharacterSelectionViewController

You can navigate to GameViewController via a Show (e.g. Push) segue. There is also a back button that goes back to MenuViewController with the following code:

[self.navigationController popViewControllerAnimated:YES];

3 - GameViewController

  1. It first shows a 5 second countdown (using NSTimer)
  2. The game starts with the character chosen in CharacterSelectionViewController
  3. The game can be paused, allowing you to quit and go back to MenuViewController via a manual Show Detail (e.g. Replace) segue.
  4. When the game ends, a manual Show (e.g. Push) segue is called that navigates to the ScoreViewController.

It's view hierarchy consists of three sets of view - one for the countdown, one for the pause menu and one for the game. These are subsequently shown/hidden. See the view hierarchy below:

GameViewController View Hierarchy

4 - ScoreViewController

This allows you to quit or restart the game. When quit it pressed it performs a Show Detail (e.g. Replace) segue to MenuViewController. If restart is pressed it performs an unwind to CharacterSelectionViewController.

Responses

Please provide answers regarding:

  • How this kind of leak could occur
  • Any observations you have from the allocation and leaks screenshots

Allocation

Below, you can see the increasing allocations as I cycle through the apps screens to repeatedly show the GameViewController. I used Mark Generation to be able to show the increase in memory allocations.

Allocations

Leaks

Here you can see the memory leak that occurred. This is ordered by size.

Leaks


Putting text in Circle as big as possible


It´s a pretty basic problem but I couldn´t find a proper solution for it. I have several circles which have text in it like you can see in the picture. The text gets loaded dynamically and has a size from one word up to five words or more. The goal is to put the text as big as possible into the circle. New lines can appear but every individual word should stay together. The example image is kind of ok but I would prefer the text to be bigger because there is still some free space between the text and the circle. The circle is 80x80. All solution I tried cropped the text strangly or the text is too small.

How I create the label:

UILabel *buttonlabel = [[UILabel alloc] initWithFrame:CGRectMake(12,7,57,64)];

    [buttonlabel setText: @"Text"];
    buttonlabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18.0f];
    buttonlabel.textColor = [UIColor whiteColor];
    buttonlabel.textAlignment = NSTextAlignmentCenter;
    buttonlabel.lineBreakMode = NSLineBreakByWordWrapping;
    buttonlabel.numberOfLines = 3;
   [button addSubview:buttonlabel];
   [buttonlabel release];

enter image description here


CGRect intersects 4 rects. How to figure out which rect it intersects mostly?


If you need more details: I have UICollectionViewCell which is draggable. When the cell overlaps other cells during dragging I want to know which one it overlaps mostly in order to replace overlapped cell with this cell. Is there any efficient way to do this? I found nothing helpful in CGGeometry. Thank you.


Creating a large GIF with CGImageDestinationFinalize - running out of memory


I'm trying to fix a performance issue when creating GIFs with lots of frames. For example some GIFs could contain > 1200 frames. With my current code I run out of memory. I'm trying to figure out how to solve this; could this be done in batches? My first idea was if it was possible to append images together but I do not think there is a method for that or how GIFs are created by the ImageIO framework. It would be nice if there was a plural CGImageDestinationAddImages method but there isn't, so I'm lost on how to try to solve this. I appreciate any help offered. Sorry in advance for the lengthy code, but I felt it was necessary to show the step by step creation of the GIF.

It is acceptable that I can make a video file instead of a GIF as long as the differing GIF frame delays are possible in a video and recording doesn't take as long as the GIF animation.

Note: jump to Latest Update heading below to skip the backstory.

Updates 1 - 6: Thread lock fixed by using GCD, but the memory issue still remains. 100% CPU utilization is not the concern here, as I show a UIActivityIndicatorView while the work is performed. Using the drawViewHierarchyInRect method might be more efficient/speedy than the renderInContext method, however I discovered you can't use the drawViewHierarchyInRect method on a background thread with the afterScreenUpdates property set to YES; it locks up the thread.

There must be some way of writing the GIF out in batches. I believe I've narrowed the memory problem down to: CGImageDestinationFinalize This method seems pretty inefficient for making images with lots of frames since everything has to be in memory to write out the entire image. I've confirmed this because I use little memory while grabbing the rendered containerView layer images and calling CGImageDestinationAddImage. The moment I call CGImageDestinationFinalize the memory meter spikes up instantly; sometimes up to 2GB based on the amount of frames. The amount of memory required just seems crazy to make a ~20-1000KB GIF.

Update 2: There is a method I found that might promise some hope. It is:

CGImageDestinationCopyImageSource(CGImageDestinationRef idst, 
CGImageSourceRef isrc, CFDictionaryRef options,CFErrorRef* err) 

My new idea is that for every 10 or some other arbitrary # of frames, I will write those to a destination, and then in the next loop, the prior completed destination with 10 frames will now be my new source. However there is a problem; reading the docs it states this:

Losslessly copies the contents of the image source, 'isrc', to the * destination, 'idst'. 
The image data will not be modified. No other images should be added to the image destination. 
* CGImageDestinationFinalize() should not be called afterward -
* the result is saved to the destination when this function returns.

This makes me think my idea won't work, but alas I tried. Continue to Update 3.

Update 3: I've been trying the CGImageDestinationCopyImageSource method with my updated code below, however I'm always getting back an image with only one frame; this is because of the documentation stated in Update 2 above most likely. There is yet one more method to perhaps try: CGImageSourceCreateIncremental But I doubt that is what I need.

It seems like I need some way of writing/appending the GIF frames to disk incrementally so I can purge each new chunk out of memory. Perhaps a CGImageDestinationCreateWithDataConsumer with the appropriate callbacks to save the data incrementally would be ideal?

Update 4: I started to try the CGImageDestinationCreateWithDataConsumer method to see if I could manage writing the bytes out as they come in using an NSFileHandle, but again the problem is that calling CGImageDestinationFinalize sends all of the bytes in one shot which is the same as before - I run out memory. I really need help to get this solved and will offer a large bounty.

Update 5: I've posted a large bounty. I would like to see some brilliant solutions without a 3rd party library or framework to append the raw NSData GIF bytes to each other and write it out incrementally to disk with an NSFileHandle - essentially creating the GIF manually. Or, if you think there is a solution to be found using ImageIO like what I've tried that would be amazing too. Swizzling, subclassing etc.

Update 6: I have been researching how GIFs are made at the lowest level, and I wrote a small test which is along the lines of what I'm going for with the bounty's help. I need to grab the rendered UIImage, get the bytes from it, compress it using LZW and append the bytes along with some other work like determining the global color table. Source of info: http://ift.tt/1JoQ77k .

Latest Update:

I've spent all week researching this from every angle to see what goes on exactly to build decent quality GIFs based on limitations (such as 256 colors max). I believe and assume what ImageIO is doing is creating a single bitmap context under the hood with all image frames merged as one, and is performing color quantization on this bitmap to generate a single global color table to be used in the GIF. Using a hex editor on some successful GIFs made from ImageIO confirms they have a global color table and never have a local one unless you set it for each frame yourself. Color quantization is performed on this huge bitmap to build a color palette (again assuming, but strongly believe).

I have this weird and crazy idea: The frame images from my app can only differ by one color per frame and even better yet, I know what small sets of colors my app uses. The first/background frame is a frame that contains colors that I cannot control (user supplied content such as photos) so what I'm thinking is I will snapshot this view, and then snapshot another view with that has the known colors my app deals with and make this a single bitmap context that I can pass into the normal ImaegIO GIF making routines. What's the advantage? Well, this gets it down from ~1200 frames to one by merging two images into a single image. ImageIO will then do its thing on the much smaller bitmap and write out a single GIF with one frame.

Now what can I do to build the actual 1200 frame GIF? I'm thinking I can take that single frame GIF and extract the color table bytes nicely, because they fall between two GIF protocol blocks. I will still need to build the GIF manually, but now I shouldn't have to compute the color palette. I will be stealing the palette ImageIO thought was best and using that for my byte buffer. I still need an LZW compressor implementation with the bounty's help, but that should be alot easier than color quantization which can be painfully slow. LZW can be slow too so I'm not sure if it's even worth it; no idea how LZW will perform sequentially with ~1200 frames.

What are your thoughts?

@property (nonatomic, strong) NSFileHandle *outputHandle;    

- (void)makeGIF
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^
    {
        NSString *filePath = @"/Users/Test/Desktop/Test.gif";

        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

        self.outputHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

        NSMutableData *openingData = [[NSMutableData alloc]init];

        // GIF89a header

        const uint8_t gif89aHeader [] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };

        [openingData appendBytes:gif89aHeader length:sizeof(gif89aHeader)];


        const uint8_t screenDescriptor [] = { 0x0A, 0x00, 0x0A, 0x00, 0x91, 0x00, 0x00 };

        [openingData appendBytes:screenDescriptor length:sizeof(screenDescriptor)];


        // Global color table

        const uint8_t globalColorTable [] = { 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00 };

        [openingData appendBytes:globalColorTable length:sizeof(globalColorTable)];


        // 'Netscape 2.0' - Loop forever

        const uint8_t applicationExtension [] = { 0x21, 0xFF, 0x0B, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00 };

        [openingData appendBytes:applicationExtension length:sizeof(applicationExtension)];

        [self.outputHandle writeData:openingData];

        for (NSUInteger i = 0; i < 1200; i++)
        {
            const uint8_t graphicsControl [] = { 0x21, 0xF9, 0x04, 0x04, 0x32, 0x00, 0x00, 0x00 };

            NSMutableData *imageData = [[NSMutableData alloc]init];

            [imageData appendBytes:graphicsControl length:sizeof(graphicsControl)];


            const uint8_t imageDescriptor [] = { 0x2C, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x0A, 0x00, 0x00 };

            [imageData appendBytes:imageDescriptor length:sizeof(imageDescriptor)];


            const uint8_t image [] = { 0x02, 0x16, 0x8C, 0x2D, 0x99, 0x87, 0x2A, 0x1C, 0xDC, 0x33, 0xA0, 0x02, 0x75, 0xEC, 0x95, 0xFA, 0xA8, 0xDE, 0x60, 0x8C, 0x04, 0x91, 0x4C, 0x01, 0x00 };

            [imageData appendBytes:image length:sizeof(image)];


            [self.outputHandle writeData:imageData];
        }


        NSMutableData *closingData = [[NSMutableData alloc]init];

        const uint8_t appSignature [] = { 0x21, 0xFE, 0x02, 0x48, 0x69, 0x00 };

        [closingData appendBytes:appSignature length:sizeof(appSignature)];


        const uint8_t trailer [] = { 0x3B };

        [closingData appendBytes:trailer length:sizeof(trailer)];


        [self.outputHandle writeData:closingData];

        [self.outputHandle closeFile];

        self.outputHandle = nil;

        dispatch_async(dispatch_get_main_queue(),^
        {
           // Get back to main thread and do something with the GIF
        });
    });
}

- (UIImage *)getImage
{
    // Read question's 'Update 1' to see why I'm not using the
    // drawViewHierarchyInRect method
    UIGraphicsBeginImageContextWithOptions(self.containerView.bounds.size, NO, 1.0);
    [self.containerView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Shaves exported gif size considerably
    NSData *data = UIImageJPEGRepresentation(snapShot, 1.0);

    return [UIImage imageWithData:data];
}