Rectangle 27 5

Use your swift file in objective c file.

  • Use your swift file in objective c file.
  • Use your objective c file in swift file.
  • Add your swift file in an objective-c project or vice-versa.

Go to Build Settings and perform below steps with search,

  • search for this text "brid" and set a path of your header file.
  • "Always Embed Swift Standard Libraries" : YES.
  • "Install Objective-C Compatibility Header" : YES.

In that case,First write "@objc" before your class in swift file.

After that ,In your objective c file, write this,

#import "YourProjectName-Swift.h"

In that case, In your header file, write this,

#import "YourObjective-c_FileName.h"

ios - Can't use Swift classes inside Objective-C - Stack Overflow

ios objective-c swift
Rectangle 27 5

Use your swift file in objective c file.

  • Use your swift file in objective c file.
  • Use your objective c file in swift file.
  • Add your swift file in an objective-c project or vice-versa.

Go to Build Settings and perform below steps with search,

  • search for this text "brid" and set a path of your header file.
  • "Always Embed Swift Standard Libraries" : YES.
  • "Install Objective-C Compatibility Header" : YES.

In that case,First write "@objc" before your class in swift file.

After that ,In your objective c file, write this,

#import "YourProjectName-Swift.h"

In that case, In your header file, write this,

#import "YourObjective-c_FileName.h"

ios - Can't use Swift classes inside Objective-C - Stack Overflow

ios objective-c swift
Rectangle 27 5

Use your swift file in objective c file.

  • Use your swift file in objective c file.
  • Use your objective c file in swift file.
  • Add your swift file in an objective-c project or vice-versa.

Go to Build Settings and perform below steps with search,

  • search for this text "brid" and set a path of your header file.
  • "Always Embed Swift Standard Libraries" : YES.
  • "Install Objective-C Compatibility Header" : YES.

In that case,First write "@objc" before your class in swift file.

After that ,In your objective c file, write this,

#import "YourProjectName-Swift.h"

In that case, In your header file, write this,

#import "YourObjective-c_FileName.h"

ios - Can't use Swift classes inside Objective-C - Stack Overflow

ios objective-c swift
Rectangle 27 108

The generic answer would be "as soon as you no longer need the notifications". This is obviously not a satisfying answer.

I'd recommend, that you add a call [notificationCenter removeObserver: self] in method dealloc of those classes, which you intend to use as observers, as it is the last chance to unregister an observer cleanly. This will, however, only protect you against crashes due to the notification center notifying dead objects. It cannot protect your code against receiving notifications, when your objects are not yet/no longer in a state in which they can properly handle the notification. For this... See above.

Edit (since the answer seems to draw more comments than I would have thought) All I am trying to say here is: it's really hard to give general advice as to when it's best to remove the observer from the notification center, because that depends:

  • The implementation of the observer (When is it ready to receive notifications? When is it no longer ready?)
  • The intended life-time of the observer (Is it tied to some other object, say, a view or view controller?)

So, the best general advice I can come up with: to protect your app. against at least one possible failure, do the removeObserver: dance in dealloc, since that's the last point (in the object's life), where you can do that cleanly. What this does not mean is: "just defer the removal until dealloc is called, and everything will be fine". Instead, remove the observer as soon as the object is no longer ready (or required) to receive notifications. That is the exact right moment. Unfortunately, not knowing the answers to any of the questions mentioned above, I cannot even guess, when that moment would be.

You can always safely removeObserver: an object multiple times (and all but the very first call with a given observer will be nops). So: think about doing it (again) in dealloc just to be sure, but first and foremost: do it at the appropriate moment (which is determined by your use case).

I suppose it should be noted in that one should remove observer somewhere else other than dealloc. For example, viewwilldisappear

@MobileMon -- yes. I hope, that that's the point I am getting across with my answer. Removing the observer in dealloc is only a last line of defence against crashing the app due to a later access to a decallocated object. But the proper place to unregister an observer is usually somewhere else (and often, much earlier in the object's life-cycle). I am not trying to say here "Hey, just do it in dealloc and everything will be fine".

@MobileMon "For example, viewWillDisappear" The problem with giving a concrete advise is, that it really depends on what kind of object you register as observer for what kind of event. It may be the right solution to unregister an observer in viewWillDisappear (or viewDidUnload) for UIViewControllers, but that really depends on the use case.

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 112

The information is now spread across several guides in the documentation. Here's a list of required reading:

The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS") if you don't perform proper cleanup.

Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).

Thanks dude I read the basics from Apple Dev , on my present development Having a hard time in memory management "crashed in objc_msgSend()" So i just thought of revising my understanding on properties. stackoverflow.com/questions/4506205/

Just a heads up, the link into the answer goes to a generic "Page not found" on apples site. Then it redirects to the "Mac Developer Library" This SO answer has useful info: stackoverflow.com/questions/2255861/

Kind of a difficult one to update because the documentation has changed and it's no longer in one convenient place. Feedback sent to Apple doc team.

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 112

The information is now spread across several guides in the documentation. Here's a list of required reading:

The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS") if you don't perform proper cleanup.

Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).

Thanks dude I read the basics from Apple Dev , on my present development Having a hard time in memory management "crashed in objc_msgSend()" So i just thought of revising my understanding on properties. stackoverflow.com/questions/4506205/

Just a heads up, the link into the answer goes to a generic "Page not found" on apples site. Then it redirects to the "Mac Developer Library" This SO answer has useful info: stackoverflow.com/questions/2255861/

Kind of a difficult one to update because the documentation has changed and it's no longer in one convenient place. Feedback sent to Apple doc team.

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 51

NSString *path = [[@"path+with+spaces"
    stringByReplacingOccurrencesOfString:@"+" withString:@" "]
    stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Note that the plus-for-space substitution is only used in application/x-www-form-urlencoded data - the query string part of a URL, or the body of a POST request.

there are other characters other that the + that need to be decoded, no?

When I tried to decode a string @"abcjhjhdfjhafjakhfjaklfj12346890(*^$#@@@#$%^^ ........", using this method, it returns nil. It looks like stringByReplacingPercentEscapesUsingEncoding is causing some problems because of "Returns nil if the transformation is not possible (i.e. the percent escapes give a byte sequence not legal in the given encoding). " (from NSURL.h). So just a heads up for those that ran into this issue making a category like me.

%^^ isn't a valid percent-escape.

How to URL Decode in iOS - Objective C - Stack Overflow

objective-c ios urldecode
Rectangle 27 156

NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];
components
NSLog(@"%ld", [components day]);

How exactly do we access it from components?

@RamyAlZuhouri, why would you even need f to be static?

@SpacePyro: forget it, it was an pun in response I had said somewhere else.

ios - Objective C - calculating the number of days between two dates -...

objective-c ios nsstring nsdate
Rectangle 27 37

Note : This has been tested and working 100% percent

override func viewWillDisappear(animated: Bool){
    super.viewWillDisappear(animated)

    if self.isBeingDismissed()  //presented view controller
    {
        // remove observer here
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

In iOS 6.0 > version , its better to remove observer in viewWillDisappear as viewDidUnload method is deprecated.

[[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];

There is many times its better to remove observer when the view has been removed from the navigation stack or hierarchy.

- (void)viewWillDisappear:(BOOL)animated{
 if (![[self.navigationController viewControllers] containsObject: self]) //any other hierarchy compare if it contains self or not
    {
        // the view has been removed from the navigation stack or hierarchy, back is probably the cause
        // this will be slow with a large stack however.

        [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    if ([self isBeingDismissed] == YES) ///presented view controller
    {
        // remove observer here
        [[NSNotificationCenter defaultCenter] removeObserver:observerObjectHere];
    }
}

Except a controller may still want notifications when its view is not showing (e.g. to reload a tableView).

@wcochran automatically reload/refresh in viewWillAppear:

@Prince can you explain why viewWillDisapper better then dealloc? so we have add observer to self, so when the self will be dropped from memory it will call dealloc and then all observers will be deleted, is this not a good logic.

removeObserver:self
UIViewController

Putting the removeObserver calls in viewWillDisappear as indicated is definitely the right way to go if the controller is being presented via pushViewController. If you put them in dealloc instead then dealloc will never be called -- in my experience at least...

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 28

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.

May be they will not send messages to observers, but I believe they will keep a strong reference to them as I understand. In that case all observers will stay in memory and produce a leak. orrect me if I am wrong.

The linked documentation goes into detail about that. TL;DR: it's a weak reference.

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 19

// Decode a percent escape encoded string.
- (NSString*) decodeFromPercentEscapeString:(NSString *) string {
return (__bridge NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                        (__bridge CFStringRef) string,
                                                        CFSTR(""),
                                                        kCFStringEncodingUTF8);
}

This seems to be the preferred way because... "Apparently" this is a "bug" apple is aware of, but they haven't done anything about it yet... ( http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/ )

How to URL Decode in iOS - Objective C - Stack Overflow

objective-c ios urldecode
Rectangle 27 29

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where copy refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of an object.

release Decreases the retain count of an object by 1. Relinquishes ownership of an object.

Thanks for your reply.Could you please explain 1.ClassA have a property called - (Class B*)functionName; 2.ClassB have method (void)setHeight; 3.ClassC interface I have declared ClassA *tempA as retain. 4.Class C implementation in the constructor I have this statement ClassB *tempB = tempA.functionName; 5.When I try to send a message (tempB. setHeight;) on the next line of tempB initialization my program works fine.

6.putting the same statement(tempB. setHeight;) into some function and calling the same function my program get Crashed in objc_msgSend().

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 29

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where copy refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of an object.

release Decreases the retain count of an object by 1. Relinquishes ownership of an object.

Thanks for your reply.Could you please explain 1.ClassA have a property called - (Class B*)functionName; 2.ClassB have method (void)setHeight; 3.ClassC interface I have declared ClassA *tempA as retain. 4.Class C implementation in the constructor I have this statement ClassB *tempB = tempA.functionName; 5.When I try to send a message (tempB. setHeight;) on the next line of tempB initialization my program works fine.

6.putting the same statement(tempB. setHeight;) into some function and calling the same function my program get Crashed in objc_msgSend().

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 25

If the observer is added to a view controller, I strongly recommend adding it in viewWillAppear and removing it in viewWillDisappear.

I'm curious, @RickiG: why do you recommend using viewWillAppear and viewWillDisappear for viewControllers?

@IsaacOveracker a few reasons: your setup up code (eg. loadView and viewDidLoad) could potentially cause the notifications to be fired and your controller needs to reflect that before it shows. If you do it like this there are a few benefits. At the moment you decided to "leave" the controller you don't care about the notifications and they wont cause you to do logic while the controller is being pushed off screen etc. There are special cases where the controller should receive notifications when it is off-screen I guess you can't do this. But events like that should probably be in your model.

@IsaacOveracker also with ARC it would be weird to implement dealloc to unsubscribe to notifications.

Of those what I've tried, with iOS7 this is the best way to register/remove observers when working with UIViewControllers. The only catch is that, in many cases you don't want the observer to be removed when using UINavigationController and pushing another UIViewController to the stack. Solution: You can check if the VC is being popped in viewWillDisappear by calling [self isBeingDismissed].

Popping the view controller from navigation controller may not cause dealloc to be called immediately. Going back into the view controller may then cause multiple notifications if observer is added in initialization commands.

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 18

-(void) dealloc {
      [[NSNotificationCenter defaultCenter] removeObserver:self];
      [super dealloc];
}

I'd turn the order of these instructions around... Using self after [super dealloc] makes me nervous... (even if the receiver is unlikely to actually dereference the pointer in any way, well, you never know, how they implemented NSNotificationCenter)

Dirk is right -- this is incorrect. [super dealloc] must always be the last statement of your dealloc method. It destroys your object; after it runs, you don't have a valid self anymore. /cc @Dirk

If using ARC on iOS 5+, I think [super dealloc] is not needed anymore

@pixelfreak stronger, it is not allowed under ARC to call [super dealloc]

ios - Objective C: Where to remove observer for NSNotification? - Stac...

objective-c ios nsnotifications
Rectangle 27 21

Don't look at retain counts. They're not useful and will only mislead you you can't be certain that nothing else is retaining an object, that an object you get from somewhere isn't shared.

Instead, concentrate on object ownership and follow the Cocoa memory management rules to the letter. That way your memory management will be correct no matter what optimizations Cocoa may be doing behind the scenes for you. (For example, implementing -copy as just -retain for immutable objects.)

Furthermore, it's critical to understand the difference between properties of your objects and instance variables within your objects. In your question's code, you are assigning a value to an instance variable. That instance variable is just that: a variable. Assigning to it will behave like any other variable assignment. To use the property, you must use either dot syntax or bracket syntax to actually invoke the property's setter method:

self.value = newValue;     // this is exactly equivalent to the next line
[self setValue:newValue];  // this is exactly equivalent to the previous line

The code generated for the dot syntax and the bracket syntax is identical, and neither will access the instance variable directly.

ios - Objective C NSString* property retain count oddity - Stack Overf...

ios objective-c xcode cocoa cocoa-touch
Rectangle 27 16

Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.

NSString * string ;
string = @"Your name";
- (void)setString:(NSString*)newString
{        
}

In your setter method for the property, there is a simple assignment of your instance variable to the new value,

This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.

this retains the new value in your setter method. For example: This is safer, since you explicitly state that you want to maintain a reference of the object, and you must release it before it will be deallocated.

- (void)setString:(NSString*)newString
{         
       [newString retain];         
       [string release];           
       string = newString;        
}

this makes a copy of the string in your setter method: This is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.

- (void)setString:(NSString*)newString
     {           
             if(string!=newString){             
                            [string release];             
                            string = [newString copy];           
       }
         }

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 16

Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.

NSString * string ;
string = @"Your name";
- (void)setString:(NSString*)newString
{        
}

In your setter method for the property, there is a simple assignment of your instance variable to the new value,

This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.

this retains the new value in your setter method. For example: This is safer, since you explicitly state that you want to maintain a reference of the object, and you must release it before it will be deallocated.

- (void)setString:(NSString*)newString
{         
       [newString retain];         
       [string release];           
       string = newString;        
}

this makes a copy of the string in your setter method: This is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.

- (void)setString:(NSString*)newString
     {           
             if(string!=newString){             
                            [string release];             
                            string = [newString copy];           
       }
         }

ios - Objective C - Assign, Copy, Retain - Stack Overflow

ios objective-c macos memory-management attributes
Rectangle 27 21

There is a whole guide to Date and Time Programming. Here is a relevant section which gives you a hint about what to do.

It's where the example code comes from in the other question.

Try and write something based on that and then come back if you have specific questions.

Okay. Here is how I would write the code in it's most basic form.

//  NSDate+ADNExtensions.h

#import <Cocoa/Cocoa.h>


@interface NSDate (ADNExtensions)

- (NSInteger)numberOfDaysUntil:(NSDate *)aDate;

@end
//  NSDate+ADNExtensions.m

#import "NSDate+ADNExtensions.h"


@implementation NSDate (ADNExtensions)


- (NSInteger)numberOfDaysUntil:(NSDate *)aDate {
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:self toDate:aDate options:0];

    return [components day];
}


@end

This is very rough code. There is no error checking or validating that the second date is later than the first.

And then I would use it like this (running on a 64-bit, Garbage Collected environment):

NSDate *startDate = [NSDate dateWithString:@"2010-11-01 00:00:00 +0000"];
NSDate *endDate = [NSDate dateWithString:@"2010-11-02 00:00:00 +0000"];

NSInteger difference = [startDate numberOfDaysUntil:endDate];

NSLog(@"Diff = %ld", difference);

This is such a shame, because you would have learned a lot more by posting your code and the incorrect outputs and getting more specific help. But if you just want to be a cut-and-paste programmer; take this code and good luck to you.

can you not just please provide code? honestly, I've tried many things. I've tried using Gregarian and I've tried getting an NSTimeInterval. Please just implement the method?

Robert, this isn't a "give me the code" website. Ask a question about something that you are stuck on and you will receive help to solve that problem. People aren't just going to solve your problem for you. The sooner you understand this, the sooner you can get better answers from people on Stack Overflow. I think Abizer was a bit too kind in giving you the code. ;)

btw, I am not sure that NSDate method dateWithString existed at all, but at least it was deprecated long time ago, so the second answer is more relevant, you have to use NSDateFormatter now

Heh, I came in looking for a code snippet like this, and now I'm on a big guilt trip, haha!

ios - Objective C - calculating the number of days between two dates -...

objective-c ios nsstring nsdate
Rectangle 27 10

You are passing in a literal string. The compiler probably allocates it in static memory and sets the retain count to the maximum possible value.

Try a dynamically allocated string instead and see what happens.

NSString* string = [[NSString alloc] initWithString: @"some text"];
Test* test = [[Test alloc] initWithValue: string];

it's allocating it in static memory even though i use the copy attribute on the property?

If you want to use the property, you have to say "self.value = whatever" instead of just "value = whatever", which simply assigns the instance variable.

done.. same error. i've also tried using the dynamic string code above.

ios - Objective C NSString* property retain count oddity - Stack Overf...

ios objective-c xcode cocoa cocoa-touch