1 . What is IMP in Objective C-language?

Answer :

IMP is a C type referring to the implementation of a method, also known as an implementation pointer. It's a pointer to a function returning id, and with self and a method selector (available inside method definitions as the variable _cmd) as the first arguments:


id (*IMP)(id, SEL, ...);
With NSObject, you can obtain the IMP for a given method by doing:
IMP imp=[obj methodForSelector:@selector(message)];
For Object, do:
IMP imp=[obj methodFor:@selector(message)]; 


Leave a Comment

Name  
  Email   
Message
1 . Touch ID vs Face ID code?

Answer :

You may be looking for this: biometryType is used to specify/update some localisables for user information only. Your working code will automatically identify biometryType and handle authentication operations. You don't need to update it.

Here is sample code, how you can manually detect, which biometry type is supported by device.

LAContext *laContext = [[LAContext alloc] init];

NSError *error;

if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {

    if (error != NULL) {
        // handle error
    } else {

        if (@available(iOS 11.0.1, *)) {
            if (laContext.biometryType == LABiometryTypeFaceID) {
                //localizedReason = "Unlock using Face ID"
                NSLog(@"FaceId support");
            } else if (laContext.biometryType == LABiometryTypeTouchID) {
                //localizedReason = "Unlock using Touch ID"
                NSLog(@"TouchId support");
            } else {
                //localizedReason = "Unlock using Application Passcode"
                NSLog(@"No Biometric support");
            }
        } else {
            // Fallback on earlier versions
        }


        [laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Test Reason" reply:^(BOOL success, NSError * _Nullable error) {

            if (error != NULL) {
                // handle error
            } else if (success) {
                // handle success response
            } else {
                // handle false response
            }
        }];
    }
}

2 . How to transfer Core Foundation ownership with a mix of Create/Get?
 

Answer :

According to the Get Rule I'm just getting data so I don't own it, and shouldn't be transferring ownership.

Correct, to transfer ownership you must have ownership, and you don't. Transferring ownership when you don't have it is dangerous, expect crashes.

But my reasoning is that ultimately data is being created here inside the items structure, and I'm returning it in an array so I want it to be reference-counted afterwards so I should transfer ownership.

No, what you do is just transfer the reference without ownership:

(__bridge NSData *)data

And now ARC will track the result of that expression. When you place the resulting reference in your NSMutableArray the array will take ownership. At this point your data has at least two owners, items and datas. ARC manages the lifetime of datas and any objects it refers to, however you must release items yourself when it is no longer needed. You can release it immediately after you've placed your data in datas if you do not otherwise need it.

HTH


3 . Navigation Back shows other Viewcontroller during the transition?
 

Answer :

You need to use setViewControllers method, and pass only the viewControllerA that is the first element in your navigationController.viewControllers array

Code

- (IBAction)backAction:(id)sender {
    UIViewController * viewControllerA = [self.navigationController.viewControllers firstObject]; //we get the first viewController here
    [self.navigationController setViewControllers:@[viewControllerA] animated:YES];
}

similar answer here How to start from a non-initial NavigationController scene but in swift

enter image description here


4 . Setting root view controller is not working?

Answer :

What you are trying to implement is auto login functionality (if user already logged in then no need for login page). What you are doing is correct but you also need to managed that thing from AppDelegate too.
You need to add one line to code after setting root view controller is

        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isUserLoggedIn"]; 
        // PUT this line after  [self.delegate.window makeKeyAndVisible];

You can create method in AppDelegate which monitor a boolean variable from UserDefault. and navigate to vc1 -> vc2

Put it in Appdelegate and call it from didFinishLuanchWithOptions

- (void) checkLoginStatusAndProceed {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isUserLoggedIn"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"isUserLoggedIn"] == YES) {
        // Navigate to HomeViewController
        //Make root view controller
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; //My storyboard name is Main.storyboard
        HomeViewController * hvc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"HVC"];
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:hvc];
       [self.window makeKeyAndVisible];
    }

}

5 . Embedding PNG image and other resources into OS X executable?
 

Answer :

seems you have it mostly... just grab the byte* make it into NSData and make that into an image

NSData *imageData = [NSData dataWithBytes:byteArray length:arrayLength];
NSImage *image = [[NSImage alloc] initWithData:imageData];

this assumes the pointer you have leads to valid image data ;)


you can just link into with ld (search for my github sample DDEmbeddedDataReader but any process works.. #define the array or put it in a variable in a .c file... whatever you like :)

... I wrote DDEmbeddedDataReader to see if this is worth it but I decided to just use external assets. why? you DONT want to increase binary size for resources...



6 . UIPickerView selectedRowInComponent:0 always return zero first when I try to set data in second component?

Answer :

It really seems that when the UIPickerView appears as an inputView after you have selected row 9 in component 0, the selectedRowInComponent: 0 returns 0 in numberOfRowsInComponent: 1, but then returns 9 in titleForRow: row forComponent: 1.

I don't think you are doing anything wrong, so it looks like a bug in UIKit.

As a workaround, I suggest you don't ask the picker view for the selected row, but track the selected row yourself (initialize your own variable in your view controller and update it in didSelectRow: row inComponent: 0)


7 . How Can I play local video from gallery in Avplayer ios obj c?
 

Answer :

Please use below code. You are changing the url provided by Photolibrary that's why your file failed to play.

NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

Photolibrary itself providing valid url so directly use for playing

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];

    self.imgOuter.image=img;

    [picker dismissViewControllerAnimated:YES completion:nil];
    NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

    AVPlayer *player = [AVPlayer playerWithURL:videoURL];
    AVPlayerViewController *playerViewController = [AVPlayerViewController new];
    playerViewController.player = player;
    [playerViewController.player play];
    [self presentViewController:playerViewController animated:YES completion:nil];

}

8 . TableView CheckMarks?
 

Answer :

Im utilizing the "tag" attribute to easily access the Section header in the TableView.

Something like this:

- (void)loadData {
    myData = @[
               @{
                   @"Code":@"LB3/7",
                   @"Name":@"Mixing Bale Opener LB3/7",
                   @"ParentChildType":@"P",
                   @"ParentID":[NSNull null],
                   @"ProductID":@"PRD000004",
                   @"ProductModelID":@"PMD000001",
                   @"ChildProductModels":@[
                           @{
                               @"Code":@"LB3/7-002",
                               @"Name":@"With transport apron 4.5 M",
                               @"ParentChildType":@"C",
                               @"ParentID":@"PMD000001",
                               @"ProductID":@"PRD000004",
                               @"ProductModelID":@"PMD000003"
                               },
                           @{
                               @"Code":@"LB3/7-003",
                               @"Name":@"With Magnetic Roller",
                               @"ParentChildType":@"C",
                               @"ParentID":@"PMD000001",
                               @"ProductID":@"PRD000004",
                               @"ProductModelID":@"PMD000004"
                               }
                           ]
                   },
               @{
                   @"Code":@"LB7/4",
                   @"Name":@"UNIMIX MODEL LB7/4",
                   @"ParentChildType":@"P",
                   @"ParentID":[NSNull null],
                   @"ProductID":@"PRD000004",
                   @"ProductModelID":@"PMD000005",
                   @"ChildProductModels":@[
                           @{
                               @"Code":@"LB7/4-001",
                               @"Name":@"With Beater",
                               @"ParentChildType":@"C",
                               @"ParentID":@"PMD000005",
                               @"ProductID":@"PRD000004",
                               @"ProductModelID":@"PMD000006"
                               }
                           ]
                   }
               ];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadData];
    arrSelectedRows = [NSMutableArray new];

    myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    [self.view addSubview: myTableView];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSDictionary *dictParent = [myData objectAtIndex:section];

    // Create section header (replace with custom UIView)
    UILabel *lblSectionHeader = [UILabel new];
    lblSectionHeader.tag = section + 100; // Set tag, so we can access it later
    lblSectionHeader.text = [dictParent objectForKey:@"Name"];
    return lblSectionHeader;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return myData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dictParent = [myData objectAtIndex:section];
    NSArray *arrChildren = [dictParent objectForKey:@"ChildProductModels"];
    return arrChildren.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellId"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }

    // Get the parent item
    NSDictionary *dictParent = [myData objectAtIndex:indexPath.section];

    // Get children
    NSArray *arrChildren = [dictParent objectForKey:@"ChildProductModels"];

    // Get child row info
    NSDictionary *dictItem = [arrChildren objectAtIndex:indexPath.row];

    cell.textLabel.text = [dictItem objectForKey:@"Name"];
    cell.detailTextLabel.text = [dictItem objectForKey:@"Code"];

    // Make sure accessory type is set when the rows are populated
    if ([arrSelectedRows containsObject:indexPath]) {
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    } else {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if ([arrSelectedRows containsObject:indexPath]) {
        // If the selected row was already selected, deselect it
        [arrSelectedRows removeObject:indexPath];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [cell setAccessoryType:UITableViewCellAccessoryNone];

        // Check if all children are deselected
        NSInteger numRowsInSection = [tableView numberOfRowsInSection:indexPath.section];
        BOOL areChildrenDeselected = true;
        for (NSInteger i = 0; i < numRowsInSection; i++) {
            NSIndexPath *childIndexPath = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
            if ([arrSelectedRows containsObject:childIndexPath]) {
                areChildrenDeselected = false;
            }
        }

        // Get the section header
        UILabel *lblSectionHeader = (UILabel *)[tableView viewWithTag: 100 + indexPath.section];
        if (areChildrenDeselected) {
            lblSectionHeader.textColor = [UIColor blackColor];
        } else {
            lblSectionHeader.textColor = [UIColor blueColor];
        }

    } else {
        // If the selected row wasnt selected, select it
        [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        [arrSelectedRows addObject:indexPath];
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];

        // Get section header
        UILabel *lblSectionHeader = (UILabel *)[tableView viewWithTag: 100 + indexPath.section];
        lblSectionHeader.textColor = [UIColor blueColor];
    }
}

9 . iOS - writeToFile from NSData completion handler?

Answer :

No need to worry about completion if this runs in main queue it's serial , but it's better to save in background queue and read content to verify and present in main Queue

  DispatchQueue.global(qos: .background).async {
        print("This is run on the background queue")

        if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
        {
            NSLog(@"not exists");

            NSData *fileContents = [@"" dataUsingEncoding:NSUTF8StringEncoding];
            [[NSFileManager defaultManager] createFileAtPath:filePath
                                                    contents:fileContents
                                                  attributes:nil];

        }
        else
        {
             NSLog(@"exists");

        }


        NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        [myHandle seekToEndOfFile];


        NSString*strTowrite=[NSString stringWithFormat:@"%@ || %@ --- %@ \r\n",dt,acion,name];

        [myHandle writeabilityHandler];

        [myHandle writeData:[strTowrite dataUsingEncoding:NSUTF8StringEncoding]];


    DispatchQueue.main.async {
        NSString*content=[[NSString alloc] initWithContentsOfFile:filePath
                                                         encoding:NSUTF8StringEncoding
                                                            error:&error];
         if(content)

10 . Smart rounding by number of digits in Objective-C?
 

Answer :

If leading zeroes don't count as digits

NSNumberFormatter has usesSignificantDigits, minimumSignificantDigits, and maximumSignificantDigits properties that should do what you need. Set both values to 3, or just the max if you don't want trailing zeroes on values with fewer decimal places.

If you want leading zeroes to count as digits

I'm not aware of any built-in way of handling this, but you could write some custom logic to do it. e.g.

if (yourNum < 10)
    formattedNum = [NSString stringWithFormat:@"%.2f", yourNum];
else
    formattedNum = [NSString stringWithFormat:@"%.1f", yourNum];

This is assuming the number is always between 0 and 99.whatever, so if you're not 100% confident in the data integrity you'll probably want some more checks.



11 . UITableViewCell Image change after audioplayer is finished?
 

Answer :

Retain a reference to the cell

let cellRef: IndexPath?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if messageList[indexPath.row].fileAudioUid != nil {
        let url = "..."
        startDownload(audioUrl: url)
        cellRef = indexPath

    }
}

Then

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
        print("Done")
       let cell = tableView.cellForRow(at:cellRef)
       cell.image = "myImage.png"
    } else {
        // did not finish successfully
    }
}

12 . IOS/Objective-C: UIActivityItemSource Protocol for customizing share messages with UIActivityViewController?

Answer :

I create the activity item controller with the following code:

NSArray *theItems = @[ self ];
UIActivityViewController *theController = [[UIActivityViewController alloc] initWithActivityItems:theItems applicationActivities:nil];

theController.popoverPresentationController.barButtonItem = self.shareButton;
theController.excludedActivityTypes = @[ UIActivityTypeAssignToContact,
    UIActivityTypeSaveToCameraRoll, UIActivityTypePostToFlickr,
    UIActivityTypePostToVimeo, UIActivityTypeAirDrop ];
[self presentViewController:theController animated:YES completion:NULL];

where self implements UIActivityItemSource.


13 . How can one assign an action to a user pressing on a UITableViewCell?
 

Answer :

In your DESTINATION (.h) view controller:

@property (strong, nonatomic) NSString *idDetail;

Then in your ORIGIN view controller (where you have your table):

@property int idCell;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.idCell = indexPath.row
    [self performSegueWithIdentifier:@"detailViewController" sender:sender];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"detailViewController"]) {
        SecondVC *vc = [segue destinationViewController];
        vc.idDetail = idCell;
    }
}

14 . How to specify which NSView to draw on in objective-c?
 

Answer :

You don't run this code on an NSView, rather it runs in an NSView subclass's override of the -drawRect: method.

You'll need to create your own subclass of NSView, then in that subclass, override -drawRect: and put this code there:

@interface CustomView : NSView
@end

@implementation CustomView

- (void)drawRect:(NSRect)dirtyRect
{
    NSRect r = NSMakeRect(10, 10, 50, 60);
    NSBezierPath *bp = [NSBezierPath bezierPathWithRect:r];
    NSColor *color = [NSColor blueColor];
    [color set];
    [bp stroke];
}

@end

Finally, you will of course have to instantiate an instance of CustomView and add it to your view hierarchy, just as you would normally do with a regular NSView.


15 . what is this Undefined symbols for architecture arm64 error? ios xcode?
 

Answer :

You need to add necessary framework to your project. Check all third party party framework and search its required framework for support. For e.g. if you add google analytic then you need to add CoreData , Foundation etc framework. There is some framework is missing for which third party framework needs.

Or you can-

  1. Press "Cmd+Shift+K" to clean up, and quit Xcode.
  2. Delete the cache Run "rm -rf ~/Library/Developer/Xcode/DerivedData" in terminal

  3. Open the project and re-build it

Hope this will solve your problem.