Rectangle 27 7

You can make it work with variables and a call to super.init() (for creating self before accessing its properties):

class Test: NSObject {
    var filePath: NSString!
    var _fileHandle: NSFileHandle!
    var _totalFileLength: CUnsignedLongLong!

    init?(filePath: String) {
        super.init()
        if let fileHandle = NSFileHandle(forReadingAtPath: filePath)
        {
            self.filePath = filePath
            self._fileHandle = NSFileHandle(forReadingAtPath: filePath)
            self._totalFileLength = self._fileHandle.seekToEndOfFile()
        }
        else
        {
            return nil
        }
    }
}

But if you plan to stick to your version with constants, then it's out of my comfort zone, and maybe this answer could be of help.

The super.init() was the issue - thx!

swift - All stored properties of a class instance must be initialized ...

swift xcode6.3
Rectangle 27 1

The reason why you're change fixed it is because of Apple's "safe" approach to this language. Any non-wrapped and non-initialized variables that aren't initialized before a method call will throw a compiler error. It's a safety feature in Swift. Basically, the compiler is trying to save you from doing something like this:

init(name: String, sideLength: Double){            
    super.init(name: name)
    someFunctionThatUsesSideLengthBeforeItsInitialized(sideLength)
    self.sideLength = sideLength
    numberOfSide = 4
}

This method someFunctionThatUsesSideLengthBeforeItsInitialized might cause a exception. In my opinion, super-class functions like super.init should be exempt from this rule.

ios - Swift: Order of super.init and self.attribute in init - Stack Ov...

ios osx swift swift-playground
Rectangle 27 130

If you use defer inside of an initializer, for updating any optional properties or further updating non-optional properties that you've already initialized and after you've called any super init methods, then your willSet, didSet, etc. will be called. I find this to be more convenient than implementing separate methods that you have to keep track of calling in the right places.

public class MyNewType : NSObject {
    public var myRequiredField:Int
    public var myOptionalField:Float? {
        willSet {
            if let newValue = newValue {
                print("I'm going to change to \(newValue)")
            }
        }
        didSet {
            if let myOptionalField = self.myOptionalField {
                print("Now I'm \(myOptionalField)")
            }
        }
    }

    override public init() {
        self.myRequiredField = 1

        super.init()

        // Non-defered
        self.myOptionalField = 6.28

        // Defered
        defer {
            self.myOptionalField = 3.14
        }
    }
}
I'm going to change to 3.14
Now I'm 3.14

Cheeky little trick, I like it... weird quirk of Swift though.

Great. You found another useful case of using defer. Thanks.

very interesting.. I've never seen defer used like this before. It's eloquent and works.

ios - Is it possible to allow didSet to be called during initializatio...

ios swift didset
Rectangle 27 6

  • Change properties to optionals or implicitly unwrapped optionals (not recommended)
  • Make the buildCircle() method static or just a function in the file and call the addSubview() for all the circles after all of the properties were initialized and you called super.init()
  • etc. You just have to avoid calls to self before the class was initialized.

ios - Swift. Use of 'self' in method call before all stored properties...

ios swift
Rectangle 27 3

This means that the array has not been initialized to a non-nil value.

When you put exclamation point ! after a type, you tell Swift two things:

  • It is perfectly legal for the value of gestureArray to be nil, and
  • You are going to assign a non-nil value to gestureArray prior to accessing it.
gestureArray
gestureArray.insert(...)
gestureArray!.insert(...)

From the exception that you are getting it appears that gestureArray is still nil when you call insert on it.

Can u give me an example of what I should do?

@user979331 Depending on your requirements you could make gestureArray non-optional, i.e. var gestureArray = [UIGestureRecognizer]() or add a line to initialize it, if you would like to keep it optional.

ios - Swift - unexpectedly found nil while unwrapping an Optional valu...

ios arrays swift
Rectangle 27 34

I finally found the problem: SVProgressHUD calls makeKeyAndVisible when it's initialized, because it wants to receive keyboard notifications for repositioning. I looked up what the "Key Window" actually is and found out:

Now, as the UIWindow of the SVProgressHUD was the keyWindow, my other window, which contained the UITextField did not get the user input.

I finally call makeKeyWindow on the AppDelegate's window and everything is working fine.

can we use makeKeyWindow and makeKeyAndVisible both.is that any sense or use

I don't know why I bother debugging problems like this anymore when StackOverflow always comes through. Thanks!

In my case the opposite was true. My UITextField was within a different window than the AppDelegate, but an alert brought the focus back to the AppDelegate. performing a makeKeyWindow on the correct UIWindow object fixed it for me. Thanks for pointing me in the right direction.

In my case, I grab the key window for custom popups and progress info. in iOS 6, I have to explicitly reset the makeKeyWindow to get keyboard input. ICK.

ios - UITextField not getting keyboard input - Stack Overflow

ios keyboard uitextfield ios6
Rectangle 27 2

Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.

Just exchange the two lines in init

override init()
{
    y = 123
    super.init()  
}

What's the purpose of initializing property values before calling supe...

swift
Rectangle 27 1

class MyClass: NSObject {
    var prop: String = ""

    override init() {
        super.init()
        self.setupMyProperty()
    }

    func setupMyProperty() {
        prop = "testValue"
    }
}


class MyClass1: NSObject {
    var prop: String = ""

    override init() {
        prop = MyClass1.setupMyProperty()
        super.init()
    }

    class func setupMyProperty() -> String{
        return "testValue"
    }
}

not sure I can do the same with objects instead of strings

ios - Swift. Use of 'self' in method call before all stored properties...

ios swift
Rectangle 27 3

In Objective-C, the memory allocated by alloc for a class is initialized to all-bits-zero on allocation (and then the isa ivar is set), which results in nameCell's backing ivar being set to nil by default. And since it is not an error to send a message to nil in Objective-C (the message is just ignored), you are free to just call [nameCell release] without worrying about whether nameCell was ever set.

objective c - Releasing Unused properties in iOS - Stack Overflow

objective-c ios oop properties dealloc
Rectangle 27 2

What the error is telling you, is that refresh isn't initialized. Note that you chose to make refresh not optional, which in Swift means that it has to have a value before you call super.init (or it's implicitly called, which seems to be your case). Either make refresh optional (probably what you want) or initialize it in some way.

I would suggest reading the Swift introductory documentation again, which covers this in great length.

One last thing, not part of the answer, as pointed out by @Anil, there is a built in pull to refresh control in iOS called UIRefresControl, which might be something worth looking into.

ios - How to use pull to refresh in Swift? - Stack Overflow

ios swift xcode uirefreshcontrol
Rectangle 27 3

You might want to try calling doInit in awakeFromNib however I think the frame may not have been initialized yet (didn't test that though):

Since you want to update cornerRadius with respect to view's frame, I would do that in layoutSubviews instead so any frame change will directly reflect to corner radius value:

override func awakeFromNib() {
  super.awakeFromNib()
  imageView.layer.masksToBounds = true
}

override func layoutSubviews() {
  super.layoutSubviews()
  imageView.layer.cornerRadius = frame.size.width / 2
}
awakeFromNib

Sorry should have clarified that no nib is used ... would this still help?

imageView.layer.masksToBounds = true
init(frame: CGRect)
layoutSubviews

You don't need to. You can delete it if you don't use nib file. See my update.

ios - UICollectionViewCell outlet nil in class but works after using d...

ios swift uiimageview uicollectionview uicollectionviewcell
Rectangle 27 1

1) The syntax is actually a function/closure and called Lazy Stored Property. It works like a singleton and is initialized (once) when the property is accessed the first time.

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

2) If you know that the result of an expression is never nil and the result type is always the specified type use the forced unwrapped downcast operator as! otherwise use optional bindings with the as? operator to check both for nil and the type

I'm not asking about the lazy modifier, I'm asking about the syntax {statements} followed by ()

it's a normal function syntax

function syntax is func x (args) -> returnType { } or func x ( ) { } but not func x { } ( )

iphone - Swift syntax ambiguity in Core Data stack variables in App De...

iphone swift
Rectangle 27 2

Try again to log your arrays value in a method that is called after your view is initialized, or provide a custom init method (e.g. initWithMyData: andFrame:) to solve this issue.

viewWillAppear is a UIViewController method, not a UIView method.

-(id)initWithFrame:(CGRect)frame teststring:(NSString *)ts cvsubitems:(NSMutableArray *)cvs {     self.teststring = ts;     self.cvSubitems = cvs;     ...

@PaulPounder although this may have worked it seems like you have fixed the symptom and not the problem. You should make sure you understand the answers that are given here. The init method you have in your last comment is also not of the proper recommended form and could potentially lead to some very subtle hard to trace bugs

Passing Array and String to Custom UIView Class (Subclass) (iOS) - Sta...

ios uiview uiscrollview nsmutablearray subclass
Rectangle 27 6

Normally when you receive the Initialized event (or are inside the OnInitialized override) you have access to XAML-set property values. However, UserControl classes work a little differently as they depend on InitializeComponent being called to hydrate the UI and set the related member variables, etc.

The problem is that call is in the constructor, which in turn ends up calling OnInitialized (and thus raising the Initialized event) but that happens way before the XAML-set properties have been applied, meaning you dont have access to them yet, which I needed.

One may think that's a good use for the Loaded event--to finish initialization based on those properties--but if you're performing additional initialization there, you're creating a potential race condition with your consumers in that if they subscribe to your Loaded event and get it before you, then in their handler try to access your control, they will be accessing an uninitialized control.

Then something occurred to me... As I showed above, if you remove the InitializeComponent call from the constructor, the Initialized event now works as you would expect, but of course your UI isn't hydrated yet since you haven't yet called InitializeComponent.

So what would happen if you moved that call to the beginning of the OnInitialized override, before the call to base.OnInitialized, and thus before the Initialized event was raised?

This way not only do you have the XAML-set properties, but youd also have the UI fully loaded before anyone gets the Initialized event (let alone the Loaded event), which is how the Initialized event is supposed to be used.

Below is the revised code...

public partial class TestControl : UserControl
{
    protected override void OnInitialized(EventArgs e)
    {
        InitializeComponent();
        base.OnInitialized(e);
    }

    public static readonly DependencyProperty TestValueProperty = DependencyProperty.Register(
        "TestValue",
        typeof(string),
        typeof(TestControl),
        new UIPropertyMetadata("Original Value"));

    public string TestValue
    {
        get { return (string)GetValue(TestValueProperty); }
        set { SetValue(TestValueProperty, value); }
    }

}
  • Note: You don't need the constructor anymore unless you have a specific need to do other things there. And if you do, just remember you can't access constituent controls by name until after the InitializeComponent call, but that just means you have to plan to move such name-based initialization between InitializeComponent and that call to base.OnInitialize and things will work just fine.

Worked for me on a similar situation. Thanks for the finding!

Glad I could help. This was one of those a-ha moments when I figured it out.

c# - How can you access XAML-set properties of a UserControl during in...

c# wpf user-controls initialization
Rectangle 27 3

So I managed to find a bug. It was in memory management. In my app delegate file I initialized a CoreLocationViewController and added it as a subview to my window, after that I released it and all is well. But, the releasing part was not a good way to go. After I released my ViewController, dealloc method gets called and it releases locationManager.

So the proper thing to do is not to release a ViewController that holds locationManager, or find another way of dealing with it. I'm not quite sure why that was a problem because I thought that after adding a ViewController to a window it gets retained, therefore its localtionManager gets retained as well. If anybody can clear it up for me it would be much appreciated.

No. After adding a view controller's view to a window its VIEW gets retained, but not the view itself. This is an old post, but still worth commenting on. Releasing a view controller that's on-screen will likely cause a crash when anything that happens (like a button tap) tries to call one of the methods of the view controller.

iphone - CLLocationManager never calls delegate methods - Stack Overfl...

iphone objective-c ios ios4 cllocationmanager
Rectangle 27 2

Are you sure you're looking at self.objTableView (the property's accessor method) and not objTableView (the instance variable you manually defined)? Do you have a @synthesize line? If you omitted your @synthesize line, it would have effectively done @synthesize objTableView = _objTableView; for you, defining an instance variable called _objTableView for your property called objTableView, and thus your manually defined instance variable, objTableView would never have been initialized.

It is recommended that you remove the manually defined instance variable and let the compiler synthesize that for you, and just define the property, thus:

@interface ProductsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

// Following lines removed. Do not define the instance variable.
// Let the compiler synthesize it for you.
//
// {
//     IBOutlet UITableView *objTableView;
// }

@property(nonatomic,strong)IBOutlet UITableView *objTableView;

@end

The compiler will generate the instance variable for you, and unless to manually write your own @synthesize line, the compiler will name the instance variable _objTableView. If you ever need to reference the instance variable for your objTableView property (generally only needed in initializer and dealloc methods), remember to include the leading underscore. (The convention of the underscore is to minimize chances that you accidentally refer to the instance variable when you actually intended to use the self.objTableView accessor getter method.

Hi, Thanx for your quick reply, actually I already senthesized the property @synthesize objTableView; and BTW, I tested to remove th einstance declaration as you mention above, but the table view then gt werid behaviour (cell gets disappeared when click on it). And the table view always null.

If you're manually invoking @synthesize objTableView;, then the duplicative ivar is not the issue. Still, I'd encourage you to get rid of this ivar, as this is only a source of potential confusion and it does absolutely nothing good. If you synthesized properly, commenting out the explicitly declared ivar would not affect the operation at all. If, indeed, you synthesized it as your say, the problem rests elsewhere, but you haven't shared enough to let us diagnose what's going on.

Hi Rob, I edited my pots, please have a look. My issue is not resolved and I think I should update the UI in the main thread, do you have any experience about that? Thanx in advance.

@Malloc Yes, I do a lot of multithreaded programming. And, yes, you absolutely must run all UI updates on main queue. The thing is, most well written classes (such as AFNetworking), ensure that, although they perform operations on a background queue, that the completion blocks are invoked in the main queue already, so you don't need to worry about it. If you look at the AFNetworking source, you'll see they do the requisite dispatch_async(dispatch_get_main_queue(),{...}); which sends the code represented by the ellipses to the main queue.

@Malloc So, not only is this not the problem, but this wouldn't explain why your tableview property is getting set to nil. If you want to compress your project and upload it somewhere, I can take a quick look if you want.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - Why is my tableview property null - Stack Overflow

ios uitableview
Rectangle 27 2

Are you sure you're looking at self.objTableView (the property's accessor method) and not objTableView (the instance variable you manually defined)? Do you have a @synthesize line? If you omitted your @synthesize line, it would have effectively done @synthesize objTableView = _objTableView; for you, defining an instance variable called _objTableView for your property called objTableView, and thus your manually defined instance variable, objTableView would never have been initialized.

It is recommended that you remove the manually defined instance variable and let the compiler synthesize that for you, and just define the property, thus:

@interface ProductsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

// Following lines removed. Do not define the instance variable.
// Let the compiler synthesize it for you.
//
// {
//     IBOutlet UITableView *objTableView;
// }

@property(nonatomic,strong)IBOutlet UITableView *objTableView;

@end

The compiler will generate the instance variable for you, and unless to manually write your own @synthesize line, the compiler will name the instance variable _objTableView. If you ever need to reference the instance variable for your objTableView property (generally only needed in initializer and dealloc methods), remember to include the leading underscore. (The convention of the underscore is to minimize chances that you accidentally refer to the instance variable when you actually intended to use the self.objTableView accessor getter method.

Hi, Thanx for your quick reply, actually I already senthesized the property @synthesize objTableView; and BTW, I tested to remove th einstance declaration as you mention above, but the table view then gt werid behaviour (cell gets disappeared when click on it). And the table view always null.

If you're manually invoking @synthesize objTableView;, then the duplicative ivar is not the issue. Still, I'd encourage you to get rid of this ivar, as this is only a source of potential confusion and it does absolutely nothing good. If you synthesized properly, commenting out the explicitly declared ivar would not affect the operation at all. If, indeed, you synthesized it as your say, the problem rests elsewhere, but you haven't shared enough to let us diagnose what's going on.

Hi Rob, I edited my pots, please have a look. My issue is not resolved and I think I should update the UI in the main thread, do you have any experience about that? Thanx in advance.

@Malloc Yes, I do a lot of multithreaded programming. And, yes, you absolutely must run all UI updates on main queue. The thing is, most well written classes (such as AFNetworking), ensure that, although they perform operations on a background queue, that the completion blocks are invoked in the main queue already, so you don't need to worry about it. If you look at the AFNetworking source, you'll see they do the requisite dispatch_async(dispatch_get_main_queue(),{...}); which sends the code represented by the ellipses to the main queue.

@Malloc So, not only is this not the problem, but this wouldn't explain why your tableview property is getting set to nil. If you want to compress your project and upload it somewhere, I can take a quick look if you want.

ios - Why is my tableview property null - Stack Overflow

ios uitableview
Rectangle 27 1

It sounds like you're trying to write a nil value into a dictionary or NSUserDefaults. Your controller will be initialized before viewDidLoad is called. Did you override the initializer?

ios - Why Today Notification Widget crashes at startup? - Stack Overfl...

ios ios8-today-widget
Rectangle 27 1

It sounds like you're trying to write a nil value into a dictionary or NSUserDefaults. Your controller will be initialized before viewDidLoad is called. Did you override the initializer?

ios - Why Today Notification Widget crashes at startup? - Stack Overfl...

ios ios8-today-widget
Rectangle 27 1

Variables declared in the classes interface will automatically be initialized to there default value, 0 for integral values and nil/NULL for classes and pointers. If you need to initialize the variables to other values then you need to override a guaranteed entry point for you class. A custom class inheriting from NSObject for example you will simply override init. If you are working with a view controller loaded from a NIB file then you could override initWithCoder: or awakeFromNib. You should always check the documentation for whichever class you are inheriting from and find the designated initializer for that class. Sometimes you will need to set a common initializing method and call it from various initializers. Also if you have a variable that is also a property it is recommended that you should set the property and not the variable directly.

Also if you have a variable that is also a property it is recommended that you should set the property and not the variable directly. Why ??

ios - Where should I initialize variables in objective c? - Stack Over...

objective-c ios xcode