ios,objective-c-blocks , objective-c using blocks with recursion

objective-c using blocks with recursion


Tag: ios,objective-c-blocks

I am coding an iphone app. And when I used blocks with recursion in Objective-C,
I got a warning message of

Capturing addImageToUploadEntity strongly in this block is likely to lead to a retain cycle.

I created a block called addImageToUploadEntity is used to call an async function [self.submissionEntity addImageData: toImageAlbumType: finish^{}] one by one. When it hits the base case (index <= 0), it reload the table View and return.

    __block void (^addImageToUploadEntity)(NSUInteger) = ^(NSUInteger index){
        if (index <= 0)
            [self.tableView reloadData];

        [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
            // recursively call the block with index+1

After I have researched a bit, some suggested to call the function addImageToUploadEntity() with weak type inside the block. So I rewrote this part and tried. Then, I got an error of 'bad access'.

What should I do in order to improve the code? And with this block, does it have any memory leak risk?

    __block void (^addImageToUploadEntity)(NSUInteger);
    void (^__block __weak weakaddImageToUploadEntity)(NSUInteger);

    weakaddImageToUploadEntity = addImageToUploadEntity = ^(NSUInteger index){
        if (index <= 0)
            [self.tableView reloadData];

        [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
            // recursively call the block with index+1


The asynchronous completion handler for addImageData:toImageAlbumType:finish: needs to capture a strong reference to your block. Convert the weak reference back into a strong reference, and use the strong reference inside of the asynchronous completion handler:

typedef void (^AddImageBlock)(NSUInteger);

__block __weak AddImageBlock weakAddImage = nil;

AddImageBlock addImage = ^(NSUInteger index) {
    if (index <= 0)
        [self.tableView reloadData];

    AddImageBlock strongAddImage = weakAddImage;
    [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
        // recursively call the block with index+1

weakAddImage = addImage;

The AddImageBlock will kept alive until the last asynchronous method handler is executed and released.


How to create UITableViewCells with complex content in order to keep scrolling fluent

I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

After an insert into the UITableView : custom the cell

I'm using insertion into my UITableView with this : Skill * newSkill = [[Skill alloc] init]; = @"Nouvelle compétence"; newSkill.pathPicto = @"generic"; [self.skills insertObject:newSkill atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; It works great but now I want that the inserted cell be...

Set color CFAttributedStringRef

I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate . in my...

How to get time difference based on GMT on Swift

I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

What is the best practice add video background view?

I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

Build error after I localized Info.plist

I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

Is it possible to obtain an unique iCloud user ID on cocoa?

My iOS app is currently on beta in TestFlight, and as a way to retribute to the nice people who helped me test it I would like to offer them some goodies such as, for instance, the full final version of the app for free. For this, I was thinking...

Do I have to use both of these methods?

When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

iOS 8 Swift CS193P Calculator Bug Switch Operation

I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

MFMessageComposeViewControllerDelegate not being called

I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

SpriteKit collision angle of line and circle is odd

Suppose a circle is enclosed in a diamond, and the circle heads due right. I would expect a series of continual 90 degree angles as the circle draws a square within the diamond. What I'm seeing, however, is that the circle eventually gets pushed toward the center of the diamond...

Getting video from Asset Catalog using On Demand ressources

I attributed to my .mp4 video the "tokyo" tag for example, and set it as installed during the app installation. Now before I was using a Path to get it from my resources, now it's different because it's located on the Asset Catalog. After found documentations, I tried something like...

Difference between stringByAppendingString and appendString in ios

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

NS_ENUM as property in protocol

I came across to strange behaviour. I used to have: @property (nonatomic) ApplicationState applicationState; directly in my Application class. Now it's extracted to protocol @protocol ApplicationProtocol <NSObject> @property (nonatomic) ApplicationState applicationState; ApplicationState is Enum typedef NS_ENUM(NSUInteger, ApplicationState) { ApplicationStateNormal = 0, ApplicationStateExpanded = 1, ApplicationStateMaximized = 2 }; Now. It...

App crashes when i start typing in uiseachbar in uitableview

I am making a project in which i am fetching addressbook in my tableview with the help of NSObject class. Now , I allocated a UISearchbar in it , but when i start typing , the app crashes with the following error :---- 'Can't use in/contains operator with collection (not...

animating a view on top of uitableview

I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

Unexpectedly found nil while unwrapping an Optional value - Plist

i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

NSString to NSDate doesn't work

now it works with this code: NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSDate *date = [dateFormatter dateFromString:myDate]; [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; NSString *dateString = [dateFormatter stringFromDate:date]; cell.timeLabel.text = dateString; ...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error

I have this instance method in an existing Obj-C UIImage category: - (UIImage *)applyDarkEffect; I'm trying to call it from a Swift file like so: self.backgroundImageView.image = UIImage.applyDarkEffect(image) But get this compiler error: Function produces expected type 'UIImage!'; did you mean to call it with '()'? ...

Transferring an Xcode project to another computer with all files/frameworks

I am trying to copy over my Xcode project from one computer to another but it seems to lose frameworks and the locations for the images although i copied those too. PS I am using xcode and coding an app with a friend. Is there a useful source that can...

try to recover views from custom cell

I made a custom cell from my storyboard, with an UIImageView and a UILabel. Each of them have a tag 100 for the imageView and 102 for UILabel. I try to get them in my datasource method but as below, they are still nil and I don't know why. ...

Slide in an UIButton and push other UIButton when a certain distance is reached

I would like to slide in a UIButton (grey color in screenshot) from the left to right and center it on the screen. There is an UIButton (orange color in screenshot) already though that is centered and this button should be pushed to the right and always have a distance...

iOS 9 not opening Instagram app with URL SCHEME

The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9 let instagramURL = NSURL(string: "instagram://app") Why won't the URL open?...

iOS Keyboard “Done” button load action

I'm trying to get "Done" button on to load an action, preferably the action that I have for my button. Here's the UITextField declaration let someTextField = UITextField() Trying to add a target to the textField someTextField.addTarget(self, action: "loginActionButton", forControlEvents: .EditingDidEndOnExit) ...

Implementing Applovin Ads with Swift & SpriteKit

I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

Adding Image And title both to UIsegmentControl IOS

Is there a way so that you can set both image and title of UISegmentControl simultaneously, so that image appear next to the title , just like image appear next to title in UIButton. I am trying but if I set image of Selected segment of UISegmentControl then title disappears...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

Characters and Strings in Swift

Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

How to draw each a vertex of a mesh as a circle

How to draw each a vertex of a mesh as a circle?

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

How can I show ONLY the date (and not the time) using NSDateFormatter?

I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

How to do a “show (e.g Push)” segue programatically without animation?

How can I do a "show (e.g Push)" segue programatically without animation? None of the solutions I've found works the same way as the one in storyboard.

UITapGestureRecognizer sender is the gesture, not the ui object

I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

Trying to dismiss a popover view controller with a table view inside of it

I'm trying to dismiss a popover when selecting a cell inside of it. I have created a custom delegate to support this however it is not working: In my class that houses the PopOver and table View I have the following: In .h: @protocol DismissDelegate <NSObject> -(void)didTap; @end @interface AssistanceNeededAtPopOverViewController...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

iOS: Go back to entry point view controller which is not part of navigation controller

I have a login view controller which is outside my navigation controller. When a user logs out, I want them to be back to the login view controller. I am using SWRevealViewController and Storyboards. User Flow: -> Login View Controller -> SWRevealViewController-> UINavigationController...

How can I fix crash when tap to select row after scrolling the tableview?

I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

Why doesn't a UITableView scroll until I have 2 additional rows?

Scenario: Embedded UITableView in a standard UIViewController's view. Three (3) 80-pt rows fill the UITableView. Problem: UITableView doesn't scroll until the number of rows > 5. I've tested this by varying the number of displayed rows and attempted to scroll. Three (3) rows fills the UITableView. Four (4) fills but...

Change background color of viewcontroller but not top area with clock

I want to make my whole ViewController grey except I want the top area where it shows CARRIER and the current time to remain white. Is the only way just to stick a View that covers everything except that area, and set it to grey, or is there some way...

iPod Touch (5th gen) 'Source type 1 not available' crash when using UIImagePickerControllerSourceTypeCamera

The iPod Touch (5th gen) has both a front and rear camera so why does my app crash when i try to present a UIImagePickerController with sourceType: UIImagePickerControllerSourceTypeCamera - (void)openImagePickerType:(NSString *)type { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; if([type isEqualToString:kImagePickerCameraString]) imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; if([type isEqualToString:kImagePickerLibraryString]) imagePicker.sourceType =...

ios8 Timezone parsing changed?

Has the parsing for timzones changed in iOS8? I try to parse the date "2014-09-03 12:20:38.000 +0200" with this code and get nil: -(NSDateFormatter*) dateAndTimeFormatter{ if(!_dateAndTimeFormatter){ _dateAndTimeFormatter = [[NSDateFormatter alloc]init]; [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"]; _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle; _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle; } return _dateAndTimeFormatter; } alternatively [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd...

PFUser not unwrapped - swift

I'm beginning to learn swift with parse and i've run into this error: "Value of optional type 'PFUser?' not unwrapped; did you mean to use '!' or '?' I can't seem to get it to work... PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the...

Call method after asynchronous request obj-c

In my app I init a new object, where there is method which calls NSURLConnection's sendAsynchronousRequest method. After the request, I would like to call a method in the caller UIViewController. I tried to use a static method but I then I can't control IBOutlets. How can I do this?...

Override UITabBarController Icon Selection

I'm using a standard UITabBarController with icons at the bottom, each bringing to it's ownViewController. My question is basically: Is there a way to override what happens when an icon is selected rather then directly bringing them to the view? Reason being is because I'm adding a login screen to...

UITabBarViewController doesn't rotate - iOS

I have a UITabBarViewController that contains 5 tabs and a login view which is not part of my tab bar, in my settings I have set that I support all device orientations. but when I run my app, only my login view is the only which rotates. I have created...

Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

Scaling everything up and down for different devices in UIStoryboard

Is it possible to have the storyboard scale everything up or down depending on the screen size or do I have to do it programmatically? For example the UI on iPhone 6 plus would look exactly like the one on iPhone 5 but just larger.

IOS - Adjust cell height based on content

im trying to build apps that have tableview cell similiar with twitter, there are text and images. My problem is i want to insert the image above the text. While it can be text only. So if there are no image, the text will be in position (0,0). And if...

iOS Swift: Sound not playing on iPhone Simulator

In my iOS Swift application, and i am trying to play sound on click of a button. func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) } I am running the application in iOS iPhone Simulator. I have doorbell.mp3...