Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Doc Block
Apr 15, 2003
Fun Shoe

fleshweasel posted:

Can anyone help me understand how initializers work with inheritance in Swift and Objective-C?

The situation that I have that I find strange is: I have a subclass of NSViewController with no initializers of its own. I can instantiate it in Swift by simply calling MyViewController(). However, if I try to explicitly create an initializer that calls super.init(), it errors out, saying I need to call the designated initializer which takes a bundle and a nib name. Is there an automatically generated initializer that calls the designated initializer of the superclass? How does this stuff work?

You can have convenience initializers that pass some default value to the designated initializer. Swift does not generate convenience initializers for you.

When you instantiate an object, you can call any of the available initializers (convenience or designated). NSViewController probably has overridden -init as a convenience initializer that passes default values to the -initWithNibName:bundle: designated initializer.

In your own initializers:
- convenience initializers should call self.myDesignatedInitializer() with some default values instead of super.designatedInitializer().
- designated initializers should call super.designatedInitializer()

According to this page (warning: article is from 2014), Apple's Swift iBook says:

quote:

A designated initializer must call a designated initializer from its immediate superclass.
A convenience initializer must call another initializer from the same class.
A convenience initializer must ultimately call a designated initializer.

Doc Block fucked around with this message at 05:31 on Oct 15, 2016

Adbot
ADBOT LOVES YOU

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

carry on then posted:

Awful is... awful for this.

I'm sorry. :glomp:

brap
Aug 23, 2004

Grimey Drawer
Just quoting my question for this page:

fleshweasel posted:

Can anyone help me understand how initializers work with inheritance in Swift and Objective-C?

The situation that I have that I find strange is: I have a subclass of NSViewController with no initializers of its own. I can instantiate it in Swift by simply calling MyViewController(). However, if I try to explicitly create an initializer that calls super.init(), it errors out, saying I need to call the designated initializer which takes a bundle and a nib name. Is there an automatically generated initializer that calls the designated initializer of the superclass? How does this stuff work?

I think I understand the concept of convenience and designated initializers, but am still confused by my situation. Like I said, I have an NSViewController subclass with no declared initializers. The only initializers that seem to be declared on NSViewController are failable (i.e. return type is NSViewController?), while the initializer exposed on my subclass is not failable. Which initializer on NSViewController is being called, and with what arguments?

Doc Block
Apr 15, 2003
Fun Shoe

fleshweasel posted:

Just quoting my question for this page:


I think I understand the concept of convenience and designated initializers, but am still confused by my situation. Like I said, I have an NSViewController subclass with no declared initializers. The only initializers that seem to be declared on NSViewController are failable (i.e. return type is NSViewController?), while the initializer exposed on my subclass is not failable. Which initializer on NSViewController is being called, and with what arguments?

See my post at the top of the page.

It's calling -init (NSViewController inherits from NSObject), which for NSViewController is probably overridden to be a convenience initializer that calls -initWithNibName:bundle: with some default values (probably either nil for both or the class name as the nib name).

edit: -init probably passes nil for both parameters, since from macOS 10.10 and onward, passing nil as the nib name for -initWithNibName:bundle: will cause it to use the class name as the nib name, and thus will look for "MyClassName.nib"

Doc Block fucked around with this message at 05:54 on Oct 15, 2016

brap
Aug 23, 2004

Grimey Drawer
Does that mean the generated initializer on my subclass can call a convenience initializer of the superclass? A manually written initializer can't do that, though. (I have no idea why that restriction exists.)

The designated initializer for NSViewController is also failable--so the convenience initializer must not only be calling the initializer that takes a bundle and nib name, but also applying the ! operator to it.

Doc Block
Apr 15, 2003
Fun Shoe
There is no auto-generated initializer (at least not for Objective-C objects AFAIK). If you call -init on an Objective-C object that doesn't implement its own override of that method, the runtime just looks up through the class hierarchy until it finds a superclass that does, going all the way up to NSObject if needed (which does implement -init). Same as with any other method.

NSViewController's convenience override of the -init method would be written in Objective-C. It could well be just as simple as
Objective-C code:
// in NSViewController implementation
- (nullable instancetype)init
{
    return [self initWithNibName:nil bundle:nil]
}
Convenience initializers should not be calling the superclass' initializers, convenience or designated, because they're just supposed to be designated initializers that provide some default values. Do all your initialization work in your designated initializer, and just have your convenience initializers call it.
Swift code:
convenience init() {
    self.init(userName: "Smith")
}

Doc Block fucked around with this message at 08:35 on Oct 15, 2016

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

pokeyman posted:

I'm sorry. :glomp:

I should be thanking you for being the one to remind me where everything lives lol

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
So I found and would like to use a little pod called CircleMenu, https://github.com/Ramotion/circle-menu,

I added the pod and have got it to appear and do what it should. The problem is that as I don't understand what its actually doing I dont know how to add to it. I want the 5 buttons its produces to link to new views. I have segues setup and now how to call them but I don't have a clue where to add that code. Here is my viewcontroller code.


code:

import Foundation
import UIKit
import CircleMenu
import UIColor_Hex_Swift


class CircleMenuViewController: BaseViewController, CircleMenuDelegate {
    
        let items: [(icon: String, color: UIColor)] = [
        ("icon_family", UIColor("#86dd35")),
        ("icon_friends", UIColor("#2e9df2")),
        ("icon_specialist", UIColor("#f2a02e")),
        ("icon_healthcare", UIColor("#4b2ef2")),
        ("icon_insurance", UIColor("#f22e99")),
        ]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor("#48bed2")
        
                let button = CircleMenu(
                    frame: CGRect(x: 162, y: 308, width: 50, height: 50),
                    normalIcon:"list",
                    selectedIcon:"cross",
                    buttonsCount: 5,
                    duration: 1,
                    distance: 120)
                    button.backgroundColor = UIColor.lightGray
                    button.delegate = self
                    button.layer.cornerRadius = button.frame.size.width / 2.0
                    view.addSubview(button)
        
    
 
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    // MARK: <CircleMenuDelegate>
    
    func circleMenu(_ circleMenu: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
        button.backgroundColor = items[atIndex].color
        
        button.setImage(UIImage(named: items[atIndex].icon), for: .normal)
        
        // set highlited image
        let highlightedImage  = UIImage(named: items[atIndex].icon)?.withRenderingMode(.alwaysTemplate)
        button.setImage(highlightedImage, for: .highlighted)
        button.tintColor = UIColor.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.3)
    }
    
    func circleMenu(_ circleMenu: CircleMenu, buttonWillSelected button: UIButton, atIndex: Int) {
        print("button will selected: \(atIndex)")
    }
    
    func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) {
        print("button did selected: \(atIndex)")
    }
}


pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Give your segues (different) identifiers in the storyboard editor, then depending on the button index call performSegue(withIdentifier:) with the appropriate identifier.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:

pokeyman posted:

Give your segues (different) identifiers in the storyboard editor, then depending on the button index call performSegue(withIdentifier:) with the appropriate identifier.

Sorry I wasnt clear. I know how to perform the segue. What I dont know is where to put that code? Also I have no idea how to reference each button. I am guessing
code:
 func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) {
        print("button did selected: \(atIndex)")
    }
This is something to do with it?

Doh004
Apr 22, 2007

Mmmmm Donuts...
Do you want to perform one those segues when one of the buttons from the Circle menu is selected?

If so, then yes, I'd imagine that's where you perform your segue.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
I cheated :)

code:
    func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) {
        print("button did selected: \(atIndex)")
        if atIndex == 0 {
            performSegue(withIdentifier: "CircleMenuToFamily", sender: nil)
        }
    }

thegasman2000 fucked around with this message at 17:00 on Oct 17, 2016

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
I mean that's basically the implementation I had in my head when I gave my unhelpful reply, so if you cheated then I'm on team cheating!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
A few years ago I had an idea for a 2D game and coded up a quick prototype in Cocos2D (I forget what version, but whatever was current 2.5-3 years ago). Life left me with no time to do much more on it, but I am thinking of beginning again on it. Is Cocos2D still the go-to game thing these days? Switching to something else is no big deal, since I'll be basically re-learning iOS development at this point anyway.

Doc Block
Apr 15, 2003
Fun Shoe
Cocos2D has had an... interesting history.

The short version is that it's basically dead now. Some people are trying to keep the original Cocos2D (Objective-C version) alive, but AFAIK the main developers were forced to give up when the company that had been sponsoring them went bankrupt. The guys leading the project now have some... different goals than the previous developers.

And then there's Cocos2D-X, which is Cocos2D but written in C++ (and it's an old version of Cocos2D, too, so layers are still a thing). It's being sponsored by a Chinese game developer, and some of the documentation is in pretty bad English. They brought over stuff like Objective-C's two stage initialization, which feels kinda weird in C++. And also pre-ARC Objective-C style reference counting, including autorelease. Cocos2D-X also has a weird, problematic Box2D physics integration.

Many 2D games these days seem to use Unity3D's 2D sprite system, with all the pitfalls that entails.

eschaton
Mar 7, 2007

Don't you just hate when you wind up in a store with people who are in a socioeconomic class that is pretty obviously about two levels lower than your own?
Use SpriteKit and target iOS, tvOS, and macOS too.

Doc Block
Apr 15, 2003
Fun Shoe
Last time I tried SpriteKit it felt pretty limited. Some things were easy, but having it be a black box made other things more effort than it was worth.

One day I might give it another look, because I don't care about Android support. Then again, my current game is using a custom 2D engine so I might just reuse that.

Toady
Jan 12, 2009

SpriteKit has improved a lot. They added a companion framework GameplayKit for entity-component architectures and rules-driven AI. There's even a tilemap editor in Xcode.

Doc Block
Apr 15, 2003
Fun Shoe
It's opaque physics engine doesn't do the things I need it to do, like planetary gravity and antigravity areas, but doesn't provide hooks for me to do them myself in a clean way like Chipmunk2D does. I would've had to write a function that runs after the physics engine and loops over every object, which seems like it would result in collision detection etc always being a frame behind.

Seems like SpriteKit might've gotten better in terms of custom graphic effects now that you can do your own Core Image filters, but you still can't do custom drawing.

And the last thing I would want is level creators monkeying around with the project in Xcode.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Cool. I should go try it out. The last "game" I ever made was in Starling.

Doctor w-rw-rw-
Jun 24, 2008

Apple Documentation posted:

Objective-C string constant is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string
What exactly does 'module' mean within this context? Per dylib (i.e. deduplicated within each statically-compiled whole)? If I have a constant in one .o and the same in another .o and link them together, are they deduplicated (I assume yes)?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Yes, it's done by both the compiler within a translation unit and the linker across translation units but within a linked image (dylib or executable). The linker may be blocked on certain strings, e.g. if they contain non-terminating nul characters.

Doctor w-rw-rw-
Jun 24, 2008
Thanks for the clarification!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Thanks to all for the info on SpriteKit / Cocos2d. A question about this though:

Doc Block posted:

Many 2D games these days seem to use Unity3D's 2D sprite system, with all the pitfalls that entails.

I was looking into Unity (I know nothing about it other than 'it exists') only because it seems under active development and might make ports to other platforms easier. Since I don't know what I don't know, what pitfalls are there in Unity / using it for 2D? My game has very simple gravity-based physics (object flies through space, might bounce off a thing or rebound "harder" off a rubber-band like wall) and not much else if that matters.

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

Lumpy posted:

Thanks to all for the info on SpriteKit / Cocos2d. A question about this though:


I was looking into Unity (I know nothing about it other than 'it exists') only because it seems under active development and might make ports to other platforms easier. Since I don't know what I don't know, what pitfalls are there in Unity / using it for 2D? My game has very simple gravity-based physics (object flies through space, might bounce off a thing or rebound "harder" off a rubber-band like wall) and not much else if that matters.

Language feature set lies somewhere between .Net2 and .Net3.5, with some unity specific implementation bugs. Be prepared to pay for things that arguably should be included in the engine itself. If you run into a serious issue you're kind of SOL because you're probably not paying for source access.

Other than that it's pretty easy, if opinionated, to work with.

Doc Block
Apr 15, 2003
Fun Shoe

Lumpy posted:

Thanks to all for the info on SpriteKit / Cocos2d. A question about this though:


I was looking into Unity (I know nothing about it other than 'it exists') only because it seems under active development and might make ports to other platforms easier. Since I don't know what I don't know, what pitfalls are there in Unity / using it for 2D? My game has very simple gravity-based physics (object flies through space, might bounce off a thing or rebound "harder" off a rubber-band like wall) and not much else if that matters.

What leper khan said, plus a few other things:
  • Sometimes the Unity developers drag their feet when it comes to supporting new iOS features or hardware. Like when Unity missed Apple's deadline requiring apps to have 64-bit support, despite 64-bit iPhones being available for a while and months of advance warning from Apple about the deadline, resulting in games using Unity not being able to submit updates until Unity got 64-bit iOS support out the door. Unity didn't get public, non-beta AppleTV support until about 6 months after the AppleTV was released. So there could be a new, must-have feature added to iOS (or cool new device) and your Unity-based game could take a while to be able to support it.
  • It's a huge, complex 3D engine, and that doesn't go away just because you're only using the 2D parts of it (unless you pay extra to get the version that lets you strip out unused stuff). The binary alone is enormous, and it's ridiculous when you see pixel art games with huge download sizes (partly) because of it.
  • Your game logic gets written in an old version of C#, and C# doesn't compile to native code, and those two can be a performance bottleneck, especially on mobile. Unity has tried to work around this by creating their own .NET intermediary bytecode to C++ compiler (IL2CPP), which then hands that C++ code off to your C++ compiler. As you might imagine, this is not bug free. And, apparently, newer versions of Mono are much faster, incorporate LLVM, and reduce/eliminate the need for IL2CPP on non-mobile platforms.

Doc Block fucked around with this message at 20:02 on Oct 26, 2016

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

Doc Block posted:

[*]Your game logic gets written in an old version of C#, and C# doesn't compile to native code, and those two can be a performance bottleneck, especially on mobile. Unity has tried to work around this by creating their own .NET intermediary bytecode to C++ compiler (IL2CPP), which then hands that C++ code off to your C++ compiler. As you might imagine, this is not bug free. And, apparently, newer versions of Mono are much faster, incorporate LLVM, and reduce/eliminate the need for IL2CPP on non-mobile platforms.
[/list]

Microsoft had already open-sourced their compiler and the official runtime. Then Microsoft bought Xamarin and open-sourced everything. There is literally no reason for Unity to be using their half-assed IL2CPP hack.

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

Simulated posted:

Microsoft had already open-sourced their compiler and the official runtime. Then Microsoft bought Xamarin and open-sourced everything. There is literally no reason for Unity to be using their half-assed IL2CPP hack.

They would have to spend the time to not use the things that are currently working. It isn't zero cost for them. Presumably they are doing this, as a modern .Net feature set is available in beta. I don't think they've specified their target for shipping it live.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Thanks again for all the info! SpriteKit it is....

Doc Block
Apr 15, 2003
Fun Shoe

Simulated posted:

Microsoft had already open-sourced their compiler and the official runtime. Then Microsoft bought Xamarin and open-sourced everything. There is literally no reason for Unity to be using their half-assed IL2CPP hack.

Well, there is the advantage of not having to ship the entire .NET runtime with each game, especially on mobile devices.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

Doc Block posted:

Well, there is the advantage of not having to ship the entire .NET runtime with each game, especially on mobile devices.

The Xamarin stack already has the ability to statically compile IL to assembly, that's. how they can ship on the iOS App Store.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
I have an issue with posting JSON giving a 400 error. Code looks like this...

code:
func testCreateUser() {
        
        let service = "registration"
        
        
        let parameters: [String:Any] = ["firstName": "John",
                                        "lastName": "Smith",
                                        "email": "JSmith@test.com",
                                        "password": "12345678",
                                        "region": "EU",
                                        "bundleId": Bundle.main.bundleIdentifier!,
                                        "appVersion": Bundle.main.infoDictionary?["CFBundleVersion"] as? String]
        
        
        /*
         if (registration["image"] as! String) {
         var imageName = "\(self.randomString(withLength: 16))\(String.mhp_uuid().replacingOccurrencesOf("-", withString: "")).jpg"
         parameters["image"] = (registration["image"] as! String)
         parameters["imageName"] = imageName
         }
         */
        let network:MHPNetwork = MHPNetwork.sharedInstance
        
        network.authenticate(service: service, parameters: parameters, completionHandler: {(_ success: Bool?, _ error: String?) -> Void in
            if success! {
                
                print("Registered")
                /*
                 used for testing registrations process = loop back to submit process
                 [self performSegueWithIdentifier:@"SubmitToFinish" sender:nil];
                 */
            }
            if error != nil {
                let failureStatus = ["title": "Registration failed", "message": error]
                print(failureStatus)
            }
        } )

It seems to be failing because of this...

code:

 if parameters != nil && JSONSerialization.isValidJSONObject(parameters)  {
            
            do {
                
                if !queryString {
                    
                    let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
                    let jsonLength = NSString(data: json, encoding: String.Encoding.utf8.rawValue)?.length
                    
                    request.setValue("\(UInt(jsonLength!))", forHTTPHeaderField: "Content-Length")
                    request.httpBody = json
                }
                
                
                return request
            }
            catch let JSONError as NSError {
                print("\(JSONError)")


Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



thegasman2000 posted:

I have an issue with posting JSON giving a 400 error. Code looks like this...

It's much easier to diagnose web response errors if you log out the request & response both. That's my first goto when debugging a web thing. Am I really sending what I think I am, and is it to the right URL?

Also (you might have tried it but just mentioning it for what it's worth): Double check the URL & try running the JSON you're posting through a linter (is there a hosed up character?).

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Also Content-Length should be number of bytes, not string length. (Probably not your main issue but I thought I'd mention it.)

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



pokeyman posted:

Also Content-Length should be number of bytes, not string length. (Probably not your main issue but I thought I'd mention it.)

Hopefully that'll be a thing of the past with the swift server api thingie. Rid us of the boring stuff, please!

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:

Powaqoatse posted:


Also (you might have tried it but just mentioning it for what it's worth): Double check the URL & try running the JSON you're posting through a linter (is there a hosed up character?).

I have double checked the URL, its correct, but the issue is I have no idea how to print out the JSON to run it though a linter...

I added a breakpoint and this is what I get. Looks good to me :eng99:

http://imgur.com/a/8XL4o

Edit: my boss ran my project downloaded from git and it runs perfectly WTF?

thegasman2000 fucked around with this message at 14:49 on Nov 13, 2016

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
gently caress sake it was Xcode. Boss updates to 8.1 and I stayed in 8.0. That really should have been the case surely?

Chasing my tail for 3 days because of that poo poo!

Doh004
Apr 22, 2007

Mmmmm Donuts...
How do people handle CoreData across multiple frameworks?

I want just a shared main thread context and a background context for intensive writes/reads. I have this working for one big .xcdatamodel; however, we have a bunch of frameworks broken out due to business domains. When we've put entities into the big model that reference a class from another module, CoreData is unable to actually find the class when doing any fetches/insertions.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
You can specify the module in the model, make sure you're doing that correctly?

Also I believe it's pretty easy to merge multiple models together at runtime. If it makes sense to divide your big model into per-module pieces that might work.

Adbot
ADBOT LOVES YOU

Doh004
Apr 22, 2007

Mmmmm Donuts...

pokeyman posted:

You can specify the module in the model, make sure you're doing that correctly?

Also I believe it's pretty easy to merge multiple models together at runtime. If it makes sense to divide your big model into per-module pieces that might work.

That's what we're doing, or at least attempting. I'm wondering if the framework that holds the .xcdatamodel MUST be linked with the frameworks that it references via its module? If so, we need to do some reorganizing in order to not introduce circular references (is that not a thing with Linked frameworks?)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply